Cod sursa(job #2249402)

Utilizator marcudanfDaniel Marcu marcudanf Data 29 septembrie 2018 19:20:28
Problema Parcurgere DFS - componente conexe Scor 15
Compilator cpp Status done
Runda Arhiva educationala Marime 0.68 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define NMAX 100005

using namespace std;

ifstream fin("dfs.in");
ofstream fout("dfs.out");

vector < int > g[NMAX];
queue < int > q;

bool viz[NMAX];
int n, m, nr;

int main(){
	fin >> n >> m;
	for(int i = 0; i < m; i++){
		int x, y;
		fin >> x >> y;
		g[x].push_back(y);
		g[x].push_back(x);
	}
	fin.close();
	for(int i = 1; i <= n; i++){
		if(!viz[i]){
			q.push(i);
			nr++;
			while(!q.empty()){
				int x = q.front();
				q.pop();
				for(int j = 0; j < g[x].size(); j++){
					if(!viz[g[x][j]]){
						q.push(g[x][j]);
						viz[g[x][j]] = 1;
					}
				}
			}
		}
	}
	fout << nr << '\n';
	fout.close();
	return 0;
}