Cod sursa(job #278126)

Utilizator AnaAnaBozeanu Ana AnaAna Data 12 martie 2009 09:25:38
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
   1. #include <stdio.h>  
   2.   
   3. int n, m, viz[100005], cnt;  
   4.   
   5. typedef struct nod  
   6. {  
   7.     int x;  
   8.     nod *a;  
   9. } *pNod;  
  10. pNod v[100005];  
  11.   
  12. void add(pNod &dest, int val)  
  13. {  
  14.     pNod p;  
  15.     p = new nod;  
  16.     p -> x = val;  
  17.     p -> a = dest;  
  18.     dest = p;  
  19. }  
  20.   
  21. void citire()  
  22. {  
  23.     freopen("dfs.in","r",stdin);  
  24.     freopen("dfs.out","w",stdout);  
  25.     scanf("%d %d",&n,&m);  
  26.     int i, x, y;  
  27.   
  28.     for (i = 1; i <= m; i++)  
  29.     {  
  30.         scanf("%d %d",&x,&y);  
  31.         add(v[x], y);  
  32.         add(v[y], x);  
  33.     }  
  34. }  
  35.   
  36. void DFS(int nod)  
  37. {  
  38.     pNod p;  
  39.     viz[nod] = 1;  
  40.     for (p = v[nod]; p != NULL; p = p -> a) if (!viz[p -> x]) DFS(p -> x);  
  41. }     
  42.   
  43. int main()  
  44. {  
  45.     citire();  
  46.     int i;  
  47.     for (i = 1; i <= n; i++) if (!viz[i]) { cnt++; DFS(i);}  
  48.     printf("%d\n",cnt);  
  49.     return 0;  
  50. }