Cod sursa(job #1815890)

Utilizator msciSergiu Marin msci Data 25 noiembrie 2016 21:27:11
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.98 kb
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
#include <vector>
#include <map>
#include <set>
#include <list>
#include <functional>
using namespace std;
static const int INF = 0x3f3f3f3f; static const long long INFL = 0x3f3f3f3f3f3f3f3f;
template<typename T, typename U> static void amin(T &x, U y) { if (y < x) x = y; }
template<typename T, typename U> static void amax(T &x, U y) { if (y > x) x = y; }

struct Node {
	int comp = -1;
	vector<int> adj;
	Node() { this->comp = -1; }
};

Node V[100005];
int N, M, ans;

void dfs(int index, int comp) {
	if (V[index].comp > -1) return;
	V[index].comp = comp;
	for (auto &i : V[index].adj) {
		dfs(i, comp);
	}
}

int main() {
	freopen("dfs.in", "r", stdin);
	freopen("dfs.out", "w", stdout);
	cin >> N >> M;
	for (int i = 0; i < M; i++) {
		int x, y; cin >> x >> y;
		V[x].adj.push_back(y);
		V[y].adj.push_back(x);
	}
	for (int i = 1; i <= N; i++) {
		if (V[i].comp == -1) {
			dfs(i, ans++);
		}
	}
	cout << ans << endl;
}