Cod sursa(job #2715212)

Utilizator Fatu_SamuelFatu Samuel Fatu_Samuel Data 3 martie 2021 11:37:41
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.14 kb
#include <fstream>
#include <vector>
#include <stack>
#include <bitset>

using namespace std;

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

const int nMax = 100000 + 5;

vector < int > l[nMax];
stack < int > stk;
bitset < nMax > vis;

int n, m;
int componente = 0;

void Citire()
{
    fin >> n >> m;

    for (int i = 1; i <= m; i++)
    {
        int a, b;

        fin >> a >> b;

        l[a].push_back(b); 
        l[b].push_back(a); 
    }

    
}

void Afisare()
{
    fout << componente;
}

void Dfs(int nod)
{
    stk.push(nod);
    vis[nod] = 1;

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

        for (int next : l[nod])
        {
            if (!vis[next])
            {
                stk.push(next);
                vis[next] = 1;
            }
        }
    }
}

void Rezolvare()
{
    for (int i = 1; i <= n; i++)
    {
        if (!vis[i])
        {
            Dfs(i);
            componente++;
        }
    }
}

int main()
{
    Citire();
    Rezolvare();
    Afisare();

    fin.close();
    fout.close();
    return 0;
}