Cod sursa(job #2554164)

Utilizator VanillaSoltan Marian Vanilla Data 22 februarie 2020 17:14:21
Problema Parcurgere DFS - componente conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 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=1;
vector <bool> V(MAXN);
vector <int> L[MAXN];


void BFS()
{
    queue<int> Q;
    bool allvisited = false;
    int s = 1;
    Q.push(s);
    while (!allvisited){
        rs++;
        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();
            }
        allvisited = true;
        for (int i = 1; i <=m; i++){
            if (V[i] == 0){
                s = i;
                allvisited = false;
                break;
            }
        }
        Q.push(s);
    }
}

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);
    }
    BFS();
    out << rs;
    return 0;
}