Cod sursa(job #3156410)

Utilizator adistancu10Stancu Adrian adistancu10 Data 11 octombrie 2023 16:35:30
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
//DFS
/*
#include <iostream>
#include <vector>
using namespace std;
const int NMAX = 100000;
vector <int> G[NMAX + 1];
int vis[NMAX + 1];

void DFS(int x) {
	cout << x << " ";
	vis[x] = 1;
	for (auto next : G[x]) {
		if (!vis[next])
			DFS(next);
	}
}
int main()
{
	int n, m;
	cin >> n >> m;
	for (int i = 1; i <= m; i++) {
		int x, y;
		cin >> x >> y;
		G[x].push_back(y);
		G[y].push_back(x);
	}
	DFS(1);
}
*/
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
const int NMAX = 100000;
vector <int> G[NMAX + 1];
int vis[NMAX + 1];
ifstream fin("1.txt");

void DFS(int x) {
	//cout << x << " ";
	vis[x] = 1;
	for (auto next : G[x]) {
		if (!vis[next])
			DFS(next);
	}
}
int main()
{
	int n, m;
	fin >> n >> m;
	for (int i = 1; i <= m; i++) {
		int x, y;
		fin >> x >> y;
		G[x].push_back(y);
		G[y].push_back(x);
	}
	int cc = 0;
	for (int i = 1; i <= n; i++) {
		if (!vis[i]) {
			cc++;
			DFS(i);
		}
	}
	cout << cc;
}