Cod sursa(job #154845)

Utilizator oumbraPaul Filimoon oumbra Data 11 martie 2008 15:12:29
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.78 kb
#include <cstdio>
#include <cstdlib>

int n, m;
int v[100005];

struct nod
{
	int to;
	struct nod * next;
};

struct nod * nds[100005];

void add(int from, int to)
{
	struct nod * cnod;
	
	cnod = (struct nod *) malloc(sizeof(struct nod));
	cnod->to = to;

	cnod->next = nds[from];

	nds[from] = cnod;		
}

void read()
{
	int t1, t2, i;

	freopen("dfs.in", "r", stdin);
	freopen("dfs.out", "w", stdout);

	scanf("%d%d", &n, &m);

	for(i = 0; i < m; i++)
	{
		scanf("%d%d", &t1, &t2);

		add(t1, t2);
		add(t2, t1);
	}
}

void df(int x)
{
	struct nod * cnod;

	v[x] = 1;

	cnod = nds[x];

	while(cnod)
	{
		if(!v[cnod->to])
			df(cnod->to);
		cnod = cnod->next;
	}
}

int main()
{
	read();
	
	int pc = 0, i;

	for(i = 1; i <= n; i++)
	{
		if(!v[i])	
			pc++, df(i);
	}

	printf("%d\n", pc);
	return 0;
}