Cod sursa(job #329757)

Utilizator jupanubv92Popescu Marius jupanubv92 Data 7 iulie 2009 13:58:06
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
#include<stdio.h>
#include<stdlib.h>
#define Nmx 100001

int n,m;
int viz[Nmx],post[Nmx],nr,nrf;
int *sol[Nmx];

struct nod
{
    int x;
    nod *urm;
};

nod *G[Nmx];
nod *GT[Nmx];

void add(int x,int y,int tip)
{
    nod *aux;
    aux=new nod;
    if(tip==1) aux->urm=G[x];
        else aux->urm=GT[x];
    aux->x=y;
    if(tip==1) G[x]=aux;
        else GT[x]=aux;
}

void citire()
{
    scanf("%d%d",&n,&m);
    int x,y;
    for(int i=1;i<=m;++i)
    {
        scanf("%d%d",&x,&y);
        add(x,y,1);
        add(y,x,2);
    }
}

void DFS(int x)
{
    viz[x]=1;
    for(nod *p=G[x];p;p=p->urm)
      if(!viz[p->x])
        DFS(p->x);
    post[++nr]=x;
}

void DFST(int x)
{
    viz[x]=0;
    sol[nrf][0]++;
    sol[nrf]=(int *)realloc(sol[nrf], (sol[nrf][0]+1)*sizeof(int));
    sol[nrf][sol[nrf][0]]=x;
    for(nod *p=GT[x];p;p=p->urm)
       if(viz[p->x])
        DFST(p->x);
}

void solve()
{
    for(int i=1;i<=n;++i)
        if(!viz[i])
            DFS(i);
    for(int i=n;i>0;--i)
       if(viz[post[i]])
         {
             nrf++;
             sol[nrf]=(int *)realloc(sol[nrf],sizeof(int));
             sol[nrf][0]=0;
             DFST(post[i]);
         }
    printf("%d\n",nrf);
    for(int i=1;i<=nrf;++i)
     {
        for(int j=1;j<=sol[i][0];++j)
          printf("%d ",sol[i][j]);
        printf("\n");
     }
}

int main()
{
    freopen("ctc.in","r",stdin);
    freopen("ctc.out","w",stdout);
    citire();
    solve();
    return 0;
}