Cod sursa(job #1276591)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 26 noiembrie 2014 16:42:47
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 kb
#include <bits/stdc++.h>

using namespace std;

typedef struct
{
    int urm;
    int nod;

} lista;

const int Nmax = 100000 + 1;
const int Mmax = 300000 + 1;

int vecini[Mmax];
lista G[Mmax];

int depth[Nmax], lowIndex[Nmax];
int stiva[Nmax], top;
bool onStack[Nmax];

vector <int> SCC[Nmax];

int N, M, numSCC;
int nextIndex;

void addEdge( int x, int y, int p )
{
    G[p].nod = y;
    G[p].urm = vecini[x];
    vecini[x] = p;
}

void DFS( int nod, int d )
{
    depth[nod] = lowIndex[nod] = ++nextIndex;
    stiva[ ++top ] = nod;
    onStack[nod] = 1;

    for ( int p = vecini[nod]; p != 0; p = G[p].urm )
    {
        int vecin = G[p].nod;

        if ( depth[vecin] == 0 )
        {
            DFS( vecin, d + 1 );
            lowIndex[nod] = min( lowIndex[nod], lowIndex[vecin] );
        }
        else
            if ( onStack[vecin] )
            {
                lowIndex[nod] = min( lowIndex[nod], lowIndex[vecin] );
            }
    }

    if ( depth[nod] == lowIndex[nod] )
    {
        numSCC++;
        int v;

        do
        {
            v = stiva[top--];
            onStack[v] = 0;
            SCC[numSCC].push_back( v );

        } while ( v != nod );
    }
}

int main()
{
    ifstream in("ctc.in");
    ofstream out("ctc.out");

    ios_base::sync_with_stdio( false );

    in >> N >> M;

    for ( int i = 1, a, b; i <= M; ++i )
    {
        in >> a >> b;
        addEdge( a, b, i );
    }

    for ( int i = 1; i <= N; ++i )
        if ( depth[i] == 0 )
            DFS( i, 1 );

    out << numSCC << "\n";

    for ( int i = 1; i <= numSCC; ++i )
    {
        for ( auto x: SCC[i] )
            out << x << " ";

        out << "\n";
    }

    return 0;
}