Cod sursa(job #411469)

Utilizator annonymusCornescu Andrey annonymus Data 4 martie 2010 22:02:56
Problema Parcurgere DFS - componente conexe Scor 45
Compilator cpp Status done
Runda Arhiva educationala Marime 0.96 kb
#include<iostream>
using namespace std;

unsigned int n, m, viz[100005], nr;

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

pNod v[100005];

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

void citire()
{
	FILE *fin = fopen("dfs.in", "r");
	
	fscanf(fin, "%d %d", &n, &m);
	int x, y;
	
	//viz = (unsigned int *)realloc(viz, sizeof(unsigned int) * (n + 1));
	//v = (pNod)realloc(v, sizeof(nod *) * (n * (n - 1) / 2 + 1));

	for(int i = 1; i <= n; i++)
	{
		fscanf(fin, "%d %d", &x, &y);
		
		add(v[x], y);
		add(v[y], x);
	}
	
	fclose(fin);
}

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

int main()
{
	citire();
	
	for(int i=1; i <= n; i++)
		if(!viz[i])
		{
			nr++;
			dfs(i);
		}
	
	FILE *fout = fopen("dfs.out", "w");
		
	fprintf(fout, "%d", nr);
	
	fclose(fout);
	
	//system("pause");
	return 0;
}