Cod sursa(job #1472141)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 16 august 2015 14:15:11
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.62 kb
#include <cstdio>
#include <bitset>
#include <array>

#define Nmax 100005
#define Bmax 400005
using namespace std;

array<int,Nmax> G,Stak,Gt,CTC;
array<int,Bmax> Buff,pozBuff,Next,NextT,NextC;
bitset<Nmax> used;
int DIM,vf,nctc;



void Add_Edge(int x,int y)
{
    Buff[++DIM] = y;
    Next[DIM] = G[x];
    G[x] = DIM;
    pozBuff[y] = DIM;

    Buff[++DIM] = x;
    NextT[DIM] = Gt[y];
    Gt[y] = DIM;
    pozBuff[x] = DIM;
}


int N,M;

void Read()
{
    scanf("%d%d",&N,&M);
    int a,b;
    for(int i = 1; i <= M; ++i)
    {
        scanf("%d%d",&a,&b);
        Add_Edge(a,b);
    }
}

void DFS(int k)
{
    used[k] = 1;
    for(int v = G[k]; v; v = Next[v])
        if(!used[Buff[v]])
            DFS(Buff[v]);
    Stak[++vf] = k;
}
void DFST(int k)
{
    NextC[ pozBuff[k] ] = CTC[nctc];
    CTC[ nctc ] = pozBuff[k];

    used[k] = 1;
    for(int v = Gt[k]; v; v = NextT[v])
        if(!used[Buff[v]])
            DFST(Buff[v]);


}

void Kosaraju()
{
    for(int i = 1; i <= N; ++i)
        if(!used[i])
            DFS(i);
    used = 0;
    while(vf > 0)
    {
        while(vf > 0 && used[ Stak[vf] ])
            --vf;
        if(vf == 0)
            continue;
        ++nctc;
        DFST(Stak[vf]);
    }
}

void Print()
{
    printf("%d\n",nctc);
    for(int i = 1; i <= nctc; ++i)
    {
        for(int v = CTC[i]; v; v = NextC[ v ])
            printf("%d ",Buff[v]);
        printf("\n");
    }
}

int main()
{
    freopen("ctc.in","r",stdin);
    freopen("ctc.out","w",stdout);

    Read();
    Kosaraju();
    Print();

    return 0;
}