Cod sursa(job #156119)

Utilizator pikuAnca Miihai piku Data 12 martie 2008 12:54:16
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.63 kb
#include<cstdio>

#define nmax 100010

struct edge
{
 int node;
 edge* next;
};

edge *v[nmax];
int n, m, a[nmax];

void adde(int x, int y)
{
 edge *q = new edge;
 q->node = y;
 q->next = v[x];
 v[x] = q;
}

void dfs(int x)
{
 if(a[x])
	return;
 a[x] = 1;
 edge *q = v[x];
 while(q)
 {
  dfs(q->node);
	q = q->next;
 }
}

int main()
{
 freopen("dfs.in", "r", stdin);
 freopen("dfs.out", "w", stdout);
 int i, x, y, count=0;

 scanf("%d %d", &n, &m);
 for(i=0; i<m; i++)
  {
   scanf("%d %d", &x, &y);
	 adde(x, y);
	 adde(y, x);
  }
 for(i=1; i<=n; i++)
  {
   if(!a[i])
		{
			dfs(i);
			count++;
		}
  }
 printf("%d", count);
 return 0;
}