Cod sursa(job #1587932)

Utilizator patrutoiuandreipatrutoiu andrei patrutoiuandrei Data 2 februarie 2016 17:54:32
Problema Componente tare conexe Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.44 kb
#include <fstream>
#include <vector>
#include <stack>

#define pb push_back
#define Ndim 100005
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");
int N,M,nrctc,ind,Low[Ndim],Lev[Ndim],nr;
bool VIZ[Ndim];
vector <int> G[Ndim];
vector <int> CTC[Ndim];
stack <int> Stv;
void read()
{
    int a,b;
    fin>>N>>M;
    for(int i=1;i<=M;i++)
    {
        fin>>a>>b;
        G[a].pb(b);
    }
}
void Tarjan(int dad)
{
    int son,nod;
    Low[dad] = Lev[dad] = ind++;
    VIZ[dad] = 1;
    Stv.push(dad);
    for(size_t i = 0; i<G[dad].size();i++)
    {
        son = G[dad][i];
        if(Lev[son] == 0)
        {
            Tarjan(son);
            Low[dad] = min(Low[dad],Low[son]);
        }
        else if(VIZ[son] == 1)
        {
            Low[dad] = min(Low[dad],Low[son]);
        }
    }
    if(Low[dad] == Low[son])
    {
        nrctc++;
        do
        {
            nod = Stv.top();
            Stv.pop();
            CTC[nr].pb(nod);
            VIZ[nod] = 0;
        }while(nod != dad);
    }
}
void solve()
{
    int i;
    for(i=1;i<=N;i++)
    {
        if(Lev[i] == 0)
            Tarjan(i);
    }
}
void print()
{
    int i;
    fout<<nr<<'\n';
    for(i=1;i<=nr;i++)
    {
        for(size_t j = 0;j<CTC[i].size();j++)
            fout<<CTC[i][j]<<' ';
        fout<<'\n';
    }
}
int main()
{
    read();
    solve();
    print();
    return 0;
}