Cod sursa(job #2417751)

Utilizator ALEx6430Alecs Andru ALEx6430 Data 1 mai 2019 00:10:56
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.82 kb
#include <fstream>
#include <stack>
#include <vector>
using namespace std;

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

int main()
{
    int n, m;
    in >> n >> m;

    vector<vector<int>> v(n+1,vector<int>());

    for(int i = 0; i < m; i++)
    {
        int x, y;
        in >> x >> y;

        v[x].push_back(y);
        v[y].push_back(x);
    }

    vector<bool> uz(n+1);
    int cnt = 0;

    for(int i = 1; i <= n; i++)
        if(!uz[i])
        {
            stack<int> s({i});

            while(!s.empty())
            {
                int nod = s.top();
                s.pop();

                uz[nod] = true;

                for(auto it: v[nod])
                    if(!uz[it]) s.push(it);
            }

            cnt++;
        }

    out << cnt;

    return 0;
}