Cod sursa(job #2781433)

Utilizator SandorTudorTudor Sandor SandorTudor Data 9 octombrie 2021 15:24:13
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.91 kb
#include <iostream>
#include <fstream>
#include <stack>
#include <vector>

using namespace std;

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

int n, m, x, y;
vector <int> V[100002];
stack <int> S;
int i, j, total;
int sol[100002];

void dfs (int k)
{
    int x, i;

    S.push(k);
    sol[k] = 0;

    while(!S.empty())
    {
        x = S.top();
        S.pop();

        for(i = 0; i < V[x].size(); i++)
        {
             if(sol[V[x][i]] == -1)
             {
                 sol[V[x][i]] = sol[x] + 1;
                 S.push(V[x][i]);
             }
        }
    }
}

int main()
{
    fin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        fin >> x >> y;
        V[x].push_back(y);
        V[y].push_back(x);
    }

    for(int i = 1; i <= n; i++)
        sol[i] = -1;

    for(int i = 1; i <= n; i++)
    {
        if(sol[i] == -1)
            dfs(i), total++;
    }

    fout << total;
    return 0;
}