Cod sursa(job #519990)

Utilizator radubbRadu B radubb Data 7 ianuarie 2011 09:56:34
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.75 kb
#include <iostream>
#include <fstream>
using namespace std;

#define nmax 100001
long n, m, ncc;
bool viz[nmax];

struct nod
{
	int y;
	nod *prev; // previous
}*v[nmax];

void add(nod *&dest, long val)
{
	nod *p = new nod;
	p -> y = val;
	p -> prev = dest;
	dest = p;
}

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

inline void afisare()
{
	long i;
	ofstream out("dfs.out");
	out<<ncc;
}

void dfs(int x)
{
	nod *p;
	viz[x] = true;
	for(p=v[x]; p; p=p->prev)
		if(!viz[p->y])
			dfs(p->y);
}

int main()
{
	citire();
	for(long i=1; i<=n; i++)
		if(!viz[i])
		{
			dfs(i);
			++ncc;
		}
	afisare();
	return 0;
}