Cod sursa(job #1414643)

Utilizator sergiunascaSergiu Nasca sergiunasca Data 2 aprilie 2015 20:43:25
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include <stdio.h>
#include <vector>
#include <stack>
#define NMax 100010
using namespace std;
int n,m,x,y,contor;
std::vector<int> G[NMax],GT[NMax],sol[NMax];
std::stack<int> stiva;
bool viz[NMax];
void DFS(int x0)
{
    viz[x0] = true;
    for(int i=0;i<G[x0].size();++i)
    {
        if(!viz[G[x0][i]])
        {
            x = G[x0][i];
            DFS(x);
        }
    }
    stiva.push(x0);
}
void DFST(int x0)
{
    viz[x0] = true;
    for(int i=0;i<GT[x0].size();++i)
    {
        if(!viz[GT[x0][i]])DFST(GT[x0][i]);
    }
    sol[contor].push_back(x0);
}
int main()
{
    freopen("ctc.in","r",stdin);
    freopen("ctc.out","w",stdout);
    scanf("%d %d",&n,&m);
    for(int i=1;i<=m;++i)
    {
        scanf("%d %d",&x,&y);
        G[x].push_back(y);
        GT[y].push_back(x);
    }
    for(int i=1;i<=n;++i)
    {
        if(!viz[i])DFS(i);
    }
    for(int i=1;i<=n;++i)viz[i] = false;
    while(!stiva.empty())
    {
        x = stiva.top();
        stiva.pop();
        if(!viz[x])
        {
            contor++;
            DFST(x);
        }
    }
    printf("%d\n",contor);
    for(int i=1;i<=contor;++i)
    {
        for(int j=0;j<sol[i].size();++j)printf("%d ",sol[i][j]);
        printf("\n");
    }
    return 0;
}