Cod sursa(job #2663599)

Utilizator Rares31100Popa Rares Rares31100 Data 26 octombrie 2020 20:54:56
Problema Componente biconexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <bits/stdc++.h>

using namespace std;

ifstream in("biconex.in");
ofstream out("biconex.out");
int n, m, vf[400001], urm[400001], last[100001], nr;

void adauga(int from, int to)
{
    vf[++nr] = to;
    urm[nr] = last[from];
    last[from] = nr;
}

int nivel[100001], minNivel[100001], stiva[100001], nrs;
int vfSol[200001], urmSol[200001], lastSol[150001], nrSol, nrComp;
bitset <100001> viz;

void adaugaSol(int to)
{
    vfSol[++nrSol] = to;
    urmSol[nrSol] = lastSol[nrComp];
    lastSol[nrComp] = nrSol;
}

void dfs(int nod = 1, int from = 0, int nv = 1)
{
    nivel[nod] = nv;
    minNivel[nod] = nv;
    viz[nod] = 1;
    stiva[++nrs] = nod;

    for(int k = last[nod]; k; k = urm[k])
        if(vf[k] != from && viz[vf[k]])
            minNivel[nod] = min(minNivel[nod], nivel[vf[k]]);
        else if(vf[k] != from)
        {
            dfs(vf[k], nod, nv + 1);
            minNivel[nod] = min(minNivel[nod], minNivel[vf[k]]);

            if(nivel[nod] <= minNivel[vf[k]])
            {
                nrComp++;
                adaugaSol(nod);
                adaugaSol(vf[k]);

                while(stiva[nrs] != vf[k])
                    adaugaSol(stiva[nrs--]);

                nrs--;
            }
        }
}

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

    for(int i, j, k = 1; k <= m; k++)
    {
        in >> i >> j;
        adauga(i, j);
        adauga(j, i);
    }

    dfs();
    out << nrComp << '\n';

    for(int i = 1; i <= nrComp; i++)
    {
        for(int k = lastSol[i]; k; k = urmSol[k])
            out << vfSol[k] << ' ';

        out << '\n';
    }

    return 0;
}