Cod sursa(job #146359)

Utilizator bogdan2412Bogdan-Cristian Tataroiu bogdan2412 Data 1 martie 2008 16:37:27
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.61 kb
#include <cstdio>
#include <vector>
#include <algorithm>

using namespace std;

#define MAXN 100005
int N, M;

vector<int> con[MAXN];
vector<bool> used;

inline void dfs( int k )
{
	if (used[k])
		return;
	used[k] = 1;

	for_each( con[k].begin(), con[k].end(), dfs );
}

int main()
{
	freopen("dfs.in", "rt", stdin);
	freopen("dfs.out", "wt", stdout);

	for (scanf("%d %d", &N, &M); M; M--)
	{
		int x, y;
		scanf("%d %d", &x, &y); x--; y--;

		con[x].push_back(y);
		con[y].push_back(x);
	}
	used.resize(N);

	int Nr = 0;
	for (int i = 0; i < N; i++)
		if (!used[i])
			dfs(i),
			Nr++;
	printf("%d\n", Nr);

	return 0;
}