Graph Theory
code for adjacency matrix
#include<iostream>
using namespace std;
int main(){
int x,y,node,edge;
cin>>node>>edge;
int a[10][10]={0};
for(int i=0;i<edge;i++){
cin>>x>>y;
a[x][y]=1;
}
}
#include<iostream>
using namespace std;
int main(){
int x,y,node,edge;
cin>>node>>edge;
int a[10][10]={0};
for(int i=0;i<edge;i++){
cin>>x>>y;
a[x][y]=1;
}
int r,p,q;
cin>>r;
for(int i=0;i<r;i++){
cin>>p>>q;
if(a[p][q]==1){
cout<<"YES"<<endl;
}
else cout<<"NO"<<endl;
}
}
Adjacency matrix
An adjacency matrix is a VxV binary matrix A. Element is 1 if there is an edge from vertex i to vertex j else is 0.
Note: A binary matrix is a matrix in which the cells can have only one of two possible values - either a 0 or 1.
The adjacency matrix can also be modified for the weighted graph in which instead of storing 0 or 1 in , the weight or cost of the edge will be stored.
In an undirected graph, if = 1, then = 1. In a directed graph, if = 1, then may or may not be 1.
Adjacency matrix provides constant time access (O(1) ) to determine if there is an edge between two nodes. Space complexity of the adjacency matrix is O().
The adjacency matrix of the following graph is:
i/j: 1 2 3 4
1 : 0 1 0 0
2 : 0 0 0 1
3 : 1 0 0 1
4 : 0 1 0 0
1 : 0 1 0 0
2 : 0 0 0 1
3 : 1 0 0 1
4 : 0 1 0 0

#include<iostream>
using namespace std;
int main(){
int x,y,node,edge;
cin>>node>>edge;
int a[10][10]={0};
for(int i=0;i<edge;i++){
cin>>x>>y;
a[x][y]=1;
}
}
TEST YOUR UNDERSTANDING
Edge Existence
You have been given an undirected graph consisting of nodes and edges. This graph can consist of self-loops as well as multiple edges. In addition , you have also been given queries. For each query , you shall be given 2 integers and . You just need to find if there exists an edge between node and node . If yes, print "YES" (without quotes) else , print "NO"(without quotes).
Input Format:
The first line consist of 2 integers and denoting the number of nodes and edges respectively. Each of the next lines consist of 2 integers and denoting an undirected edge between node and . The next line contains a single integer denoting the number of queries. The next Line contains 2 integers and denoting the details of the query.
Output Format
Print Q lines, the answer to each query on a new line.
Constraints:
Input Format:
The first line consist of 2 integers and denoting the number of nodes and edges respectively. Each of the next lines consist of 2 integers and denoting an undirected edge between node and . The next line contains a single integer denoting the number of queries. The next Line contains 2 integers and denoting the details of the query.
Output Format
Print Q lines, the answer to each query on a new line.
Constraints:
using namespace std;
int main(){
int x,y,node,edge;
cin>>node>>edge;
int a[10][10]={0};
for(int i=0;i<edge;i++){
cin>>x>>y;
a[x][y]=1;
}
int r,p,q;
cin>>r;
for(int i=0;i<r;i++){
cin>>p>>q;
if(a[p][q]==1){
cout<<"YES"<<endl;
}
else cout<<"NO"<<endl;
}
}
No comments:
Post a Comment