Advertisement
Guest User

Untitled

a guest
Oct 24th, 2014
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. WASTE THUIS/*
  2. ID: ashish1610
  3. PROG:
  4. LANG: C++
  5. */
  6. #include<algorithm>
  7. #include<iostream>
  8. #include<vector>
  9. #include<cstring>
  10. using namespace std;
  11. #define ll  long long int
  12. #define MOD 1000000007
  13. vector<int> adj[1000005];
  14. vector<pair<int,int> > adj1[1000005];
  15. bool visited[1000005]={false};
  16. void dfs(int nd)
  17. {
  18.     visited[nd]=true;
  19.     cout<<nd<<" ";
  20.     for(int i=0;i<adj[nd].size();++i)
  21.     {
  22.         int tmp=adj[nd][i];
  23.         if(!visited[tmp])
  24.             dfs(tmp);
  25.     }
  26. }
  27. void bfs(int nd)
  28. {
  29.     queue<int> q;
  30.     q.push(nd);
  31.     while(!q.empty())
  32.     {
  33.         int nd=q.front();
  34.         q.pop();
  35.         cout<<nd<<" ";
  36.         visited[nd]=true;
  37.         for(int i=0;i<adj[nd].size();++i)
  38.         {
  39.             int tmp=adj[nd][i];
  40.             if(!visited[tmp])
  41.                 q.push(adj[nd][i]);
  42.         }
  43.     }
  44. }
  45. int main()
  46. {
  47.     int t;
  48.     cin>>t;
  49.     while(t--)
  50.     {
  51.         for(int i=0;i<100005;++i)
  52.             adj[i].clear();
  53.         int n,m,x,y;//n no. of nodes, m edges
  54.         cin>>n>>m;
  55.         /*
  56.  
  57.             If graph is this :
  58.  
  59.  
  60.                 2
  61.                / \
  62.               1   3
  63.              / \
  64.             4   5
  65.            
  66.             Than input will be :
  67.             5 4 // 5 : no of nodes, 4 : no of edges
  68.             //these 4 are edges of graph above
  69.             2 3
  70.             2 1
  71.             1 4
  72.             1 5
  73.  
  74.         */
  75.         for(int i=0;i<m;++i)
  76.         {
  77.             cin>>x>>y;
  78.             adj[x].push_back(y);
  79.             adj[y].push_back(x);
  80.             /*.................*/
  81.             /* if edges have weights */
  82.             /*cin>>x>>y>>w;
  83.             adj1[x].push_back(make_pair(y,w));
  84.             adj1[y].push_back(make_pair(x,w));*/
  85.         }
  86.         memset(visited,false,sizeof(visited)); // to set the complete visited array as false.
  87.         cout<<"DFS traversal\n";
  88.         dfs(1);
  89.         cout<<endl;
  90.         cout<<"BFS traversal\n";
  91.         bfs(1);
  92.         cout<<endl;
  93.     }
  94.     return 0;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement