Cod sursa(job #1877832)

Utilizator borcanirobertBorcani Robert borcanirobert Data 13 februarie 2017 19:05:54
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
/*  punctaj :
    Algoritmul lui Tarjan -> se comporta foarte bine in practica
*/

#include <iostream>
#include <fstream>
#include <stack>
#include <vector>
using namespace std;

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

const int MAXN = 100005;
using VI = vector<int>;
vector<VI> G;
VI ind, low;
stack<int> st;
int N, M;
int index{1};
bool is[MAXN];
vector<vector<int>> ctc;

void ReadGraph();
void Tarjan();
void Write();
void DFS( int x );

int main()
{
    ReadGraph();
    Tarjan();
    Write();

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

void ReadGraph()
{
    int x, y;
    fin >> N >> M;
    G = vector<VI>(N + 1);
    low = ind = VI(N + 1);
    while ( M-- )
    {
        fin >> x >> y;
        G[x].push_back(y);
    }
}

void Tarjan()
{
    for ( int i = 1; i <= N; ++i )
        if ( !ind[i] )
            DFS(i);
}

void Write()
{
    fout << ctc.size() << '\n';
    for ( const auto& x : ctc )
    {
        for ( const int& y : x )
            fout << y << ' ';
        fout << '\n';
    }
}

void DFS( int x )
{
    ind[x] = low[x] = index;
    ++index;
    st.push(x); is[x] = 1;

    for ( const int& y : G[x] )
    {
        if ( !ind[y] )
        {
            DFS(y);
            low[x] = min( low[x], low[y] );
        }
        else
            if ( is[y] )
                low[x] = min( low[x], low[y] );
    }

    if ( ind[x] == low[x] )
    {
        VI c;
        int n;
        do
        {
            c.push_back( n = st.top() );
            st.pop(); is[n] = 0;
        }while ( n != x );
        ctc.push_back(c);
    }
}