Cod sursa(job #1089672)

Utilizator cricriFMI - Radu Vlad cricri Data 21 ianuarie 2014 20:56:38
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.62 kb
using namespace std;

#include<fstream>
#include<iostream>
#include<vector>

ifstream f("dfs.in");
ofstream g("dfs.out");

int n,m;

vector<int> nodeList[100001];

int componenta[100001];
int c;

void dfs(int x)
{
	componenta[x] = c;
	for(int i=0;i<nodeList[x].size();i++)
	{
		if(!componenta[nodeList[x][i]])
			dfs(nodeList[x][i]);
	}

}

int main()
{
	f>>n>>m;
	int x, y;

	for(int i=1;i<=m;i++)
	{
		f>>x>>y;
		nodeList[y].push_back(x);
		nodeList[x].push_back(y);
	}

	c=1;
	for(int i=1;i<=n;i++)
	{
		if(componenta[i] == 0)
		{
			dfs(i);
			c++;
		}

	}

	g<<c-1;
	return 0;
}