Cod sursa(job #2314410)

Utilizator andytosaAndrei Tosa andytosa Data 8 ianuarie 2019 14:27:26
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");

vector<int> v[100010];
stack<int> stiva;
stack< vector<int> > comp;
int nrComp;
int dis[100010], low[100010], onStack[100010], t;

void tarjan(int node) {
    dis[node] = low[node] = ++t;
    stiva.push(node);
    onStack[node] = 1;
    for ( auto it: v[node] ) {
        if ( dis[it] == 0 )
            tarjan(it);

        if (onStack[it] )
            low[node] = min(low[node], low[it]);
    }

    if ( dis[node] == low[node] ) {
        vector<int> c;
        int x;
        do {
            x = stiva.top();
            stiva.pop();
            onStack[x] = 0;

            c.push_back(x);
        } while ( x != node );
        comp.push(c);
        nrComp++;
    }
}

int main()
{
    int n, m, x, y;
    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        fin >> x >> y;
        v[x].push_back(y);
    }
    for (int i = 1; i <= n; i++)
        if ( dis[i] == 0 )
            tarjan(i);

    fout << nrComp << '\n';
    while ( !comp.empty() ) {
        vector<int> c = comp.top();
        comp.pop();
        for (auto it: c)
            fout << it << ' ';
        fout << '\n';
    }

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