abinash_hstu

459- Graph Connectivity.cpp

Nov 10th, 2015
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.09 KB | None | 0 0
  1. #include<cstdio>
  2. #include<cstring>
  3. #include<vector>
  4. #define M 27
  5. using namespace std;
  6. vector<int>edges[M];
  7. int color[M],v,count;
  8. void DFS_visit(int u)
  9. {
  10.     color[u]=1;
  11.     for(int i=0;i<edges[u].size();++i)
  12.     {
  13.         v=edges[u][i];
  14.         if(color[v]==0)
  15.             DFS_visit(v);
  16.     }
  17. }
  18. void DFS(int nodes)
  19. {
  20.     count=0;
  21.     for(int i=1;i<=nodes;++i)
  22.         color[i]=0;
  23.     for(int i=1;i<=nodes;++i)
  24.         if(color[i]==0)
  25.           DFS_visit(i),count++;
  26. }
  27. int main()
  28. {
  29.     int T,nodes,n1,n2,i;
  30.     char ch,dh;
  31.     scanf("%d",&T);
  32.     getchar();getchar();
  33.     for(i=1;i<=T;++i)
  34.     {
  35.         scanf("%c",&ch);getchar();
  36.         nodes=ch-64;
  37.         while(scanf("%c",&ch)==1)
  38.         {
  39.             if(ch=='\n')break;
  40.             scanf("%c",&dh);getchar();
  41.             n1=ch-64;
  42.             n2=dh-64;
  43.             edges[n1].push_back(n2);
  44.             edges[n2].push_back(n1);
  45.         }
  46.         DFS(nodes);
  47.         if(i!=1)printf("\n");
  48.         printf("%d\n",count);
  49.         for(int j=1;j<=nodes;++j)
  50.             edges[j].clear();
  51.  
  52.     }
  53.     return 0;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment