Cod sursa(job #1497625)

Utilizator tain1234andrei laur tain1234 Data 7 octombrie 2015 00:03:51
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.62 kb
#include <fstream>
#include <vector>
#include <stack>
using namespace std;
std::vector<int> Nout[100010];
int v[100010];
void dfs(int& st){
	stack<int> s1;
	s1.push(st);
	while (!s1.empty()){
		int x = s1.top();
		s1.pop();
		if (!v[x]){
			v[x] = 1;
			for (auto& i : Nout[x])
				s1.push(i);
		}
	}
}
int main(){
	std::ifstream f("dfs.in");
	std::ofstream of("dfs.out");
	int N, M, x, y;
	f >> N >> M;
	for (int i = 0; i < M; ++i){
		f >> x >> y;
		Nout[x].push_back(y);
		Nout[y].push_back(x);
	}
	M = 0;
	for (int i = 1; i <= N; ++i)
	if (!v[i]){ dfs(i); ++M; }
	of << M << "\n";
	return 0;
}