Cod sursa(job #2461789)

Utilizator Briana_NeaguNeagu Briana Briana_Neagu Data 26 septembrie 2019 09:59:10
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.81 kb
#include <bits/stdc++.h>
#define maxi 100003
using namespace std;

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

vector <int> vec[maxi];
stack <int> stiva;
bool viz[maxi];

void dfs(int nod)
{
    while (!stiva.empty())
    {
        int nod = stiva.top();
        stiva.pop();
        for (auto next : vec[nod])
            if (!viz[next])
            {
                viz[next] = 1;
                stiva.push(next);
            }
    }
}

int main()
{
    int n, m;
    f >> n >> m;
    while (m --)
    {
        int x, y;
        f >> x >> y;
        vec[x].push_back(y);
        vec[y].push_back(x);
    }
    int ans = 0;
    for (int nod = 1; nod <= n; ++ nod)
        if (!viz[nod])
        {
            ans ++;
            viz[nod] = 1;
            stiva.push(nod);
            dfs(nod);
        }
    g << ans;
}