Cod sursa(job #2554195)

Utilizator VanillaSoltan Marian Vanilla Data 22 februarie 2020 17:35:52
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.93 kb
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>

using namespace std;
ifstream in ("dfs.in");
ofstream out ("dfs.out");

const int MAXN = 100010;

int n,m,rs=0;
vector <bool> V(MAXN);
vector <int> L[MAXN];


void BFS(int s)
{
    queue<int> Q;
    Q.push(s);
    while (!Q.empty()){
        int current = Q.front();
        V[current] = 1;
        for (auto next: L[current]) {
            // cout << next << " ";
            if (!V[next]){
            Q.push(next);
            V[next] = 1;
            }
        }
        //cout << current << " ";
        Q.pop();
    }
}

int main()
{
    in >> n >> m;
    for (int i = 1; i<=m; i++){
        int x,y;
        in >> x >> y;
        L[x].push_back(y);
        L[y].push_back(x);
    }
    for (int i = 1; i<= n; i++){
        if (!V[i]){
            BFS(i);
            rs++;
        }
    }
    out << rs;
    return 0;
}