Cod sursa(job #159821)

Utilizator reSpawnPopescu Ioan reSpawn Data 14 martie 2008 14:02:00
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.67 kb
#include <fstream>

int n, m, viz[100005], cnt;

typedef struct nod
{
	int x;
	nod *a;
} *pNod;

pNod v[100005];

void add( pNod &dest, int val )
{
	pNod p;
	p = new nod;
	p->x = val;
	p->a = dest;
	dest = p;
}

void citire()
{
	std::ifstream read("dfs.in");
	read >> n >> m;
	int x, y;
	int i;
	for( i = 1; i <=m; i++)
	{
		read >> x >> y;
		add(v[x], y);
		add(v[y], x);
	}
}

void DFS(int nod)
{
	pNod p;
	viz[nod] = 1;
	for( p = v[nod]; p != NULL; p = p->a) if(!viz[p->x]) DFS(p->x);
}

int main()
{
	citire();
	int i;
	for(i = 1; i <= n; i++) if(!viz[i]) { cnt++; DFS(i); }
	std::ofstream out("dfs.out");
	out << cnt;
	return 0;
}