Cod sursa(job #638787)

Utilizator marinMari n marin Data 21 noiembrie 2011 16:57:41
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.66 kb
#include <stdio.h>
#define DIM 100002



struct nod {
	int inf;
	nod *adr;
} *L[DIM], *q;

int V[DIM], N, M, i, x, y, sol;

void dfs(int x) {
	V[x] = 1;
	for (nod *q = L[x];q!=NULL;q = q->adr) {
		if (!V[q->inf])
			dfs(q->inf);
	}
}

int main() {
	FILE *f = fopen("dfs.in","r");
	FILE *g = fopen("dfs.out","w");
	fscanf(f,"%d %d",&N, &M);
	for (i=1;i<=M;i++) {
		fscanf(f,"%d %d",&x, &y);
		q = new nod;
		q->inf = y;
		q->adr = L[x];
		L[x] = q;
		q = new nod;
		q->inf = x;
		q->adr = L[y];
		L[y] = q;
	}
	fclose(f);
	
	for (i=1;i<=N;i++) {
		if (!V[i]) {
			sol++;
			dfs(i);
		}
	}
	
	fprintf(g,"%d\n",sol);
	
	return 0;
}