Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- #define endl "\n"
- #define ll long long
- #define PI acos(-1.0)
- #define test cout<<"\n****\n"
- #define LCM(a,b) ((a/__gcd(a,b))*b)
- #define precise fixed(cout);cout<<setprecision(12)
- #define fast ios_base :: sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
- #define MAX 100
- vector<int> graph[MAX+10];
- int distan[MAX+10];
- void BFS(int root,int numNode){
- memset(distan,-1,sizeof(distan));
- distan[root] = 0;
- queue<int> que;
- que.push(root);
- while (!que.empty()){
- int parent = que.front();
- que.pop();
- for (int i=0;i<graph[parent].size();i++) {
- int child = graph[parent][i];
- if (distan[child]==-1){
- distan[child] = distan[parent] + 1;
- que.push(child);
- }
- }
- }
- for(int i=1;i<=numNode;i++){
- cout<<i<<"->"<<distan[i]<<endl;
- }
- }
- void ConnectedAmong(int numNode){
- for(int i=1;i<=numNode;i++){
- cout<<i<<"->";
- if(graph[i].size()==0){
- cout<<"NULL";
- } else {
- for (int j = 0; j < graph[i].size(); j++) {
- cout << graph[i][j] << " ";
- }
- }
- cout<<endl;
- }
- }
- int main(){
- int numNode,numEdge;
- cin>>numNode>>numEdge;
- for(int i=0;i<numEdge;i++){
- int node,edge;
- cin>>node>>edge;
- graph[node].push_back(edge);
- }
- cout<<"The graph is Connected among: \n";
- ConnectedAmong(numNode);
- cout<<endl;
- cout<<"Enter the root of your graph: ";
- int root;
- cin>>root;
- cout<<endl;
- cout<<"Distance of every node from root: \n";
- BFS(root,numNode);
- }
- *************************************************************************************
- **************************************NSUPS******************************************
- #include<bits/stdc++.h>
- using namespace std;
- #define endl "\n"
- #define ll long long
- #define PI acos(-1.0)
- #define test cout<<"\n****\n"
- #define LCM(a,b) ((a/__gcd(a,b))*b)
- #define precise fixed(cout);cout<<setprecision(20)
- #define fast ios_base :: sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
- const int N = 100;
- vector <int> graph[ N ];
- int dist[ N ]; // dist of every node from the source
- void bfs(int source) {
- memset(dist, -1, sizeof(dist));
- queue <int> q;
- dist[source] = 0;
- q.push(source);
- while (!q.empty()) {
- int f = q.front();
- q.pop();
- for (int i = 0; i < graph[f].size(); i++) {
- int child = graph[f][i];
- if (dist[child] == -1) {
- dist[child] = dist[f] + 1;
- q.push(child);
- }
- }
- }
- for (int i = 1; i <= 10; i++) cout << dist[i] << endl;
- }
- int main() {
- graph[1].push_back(2);
- graph[1].push_back(4);
- graph[1].push_back(3);
- graph[2].push_back(6);
- graph[4].push_back(7);
- graph[3].push_back(7);
- graph[3].push_back(8);
- graph[6].push_back(10);
- graph[8].push_back(7);
- graph[7].push_back(9);
- graph[8].push_back(5);
- graph[10].push_back(9);
- graph[10].push_back(5);
- bfs(1);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement