Cod sursa(job #2829494)

Utilizator Paul0516Berindeie Paul Paul0516 Data 8 ianuarie 2022 17:43:05
Problema Parcurgere DFS - componente conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <iostream>
#include <fstream>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <queue>
#include <stack>

using namespace std;

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

stack <int> s;

int start[500002], t[2][500002], fr[500001];

bool ver(int nr)
{
    while (nr != 0)
    {
        if (fr[t[0][nr]] == 0)
            return 1;
        nr = t[1][nr];
    }
    return 0;
}

int alege(int nr)
{
    while (nr != 0)
    {
        if (fr[t[0][nr]] == 0)
        {
            fr[t[0][nr]] = 1;
            return t[0][nr];
        }
        nr = t[1][nr];
    }
}

int main()
{
    int n, m, a, b, z = 0, contor = 0, nr;
    bool ok;
    f >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        f >> a >> b;
        z++;
        t[0][z] = a;
        t[1][z] = start[b];
        start[b] = z;
        z++;
        t[0][z] = b;
        t[1][z] = start[a];
        start[a] = z;
    }
    for (int i = 1; i <= n; i++)
    {
        if (fr[i] == 0)
            s.push(i);
        fr[i] = 1;
        ok = 1;
        while (s.empty() == 0)
        {
            if (ver(start[s.top()]) == 1)
            {
                s.push(alege(start[s.top()]));
            }
            else
                s.pop();
            ok = 0;
        }
        if (ok == 0)
            contor++;
    }
    g << contor;
    return 0;
}