Cod sursa(job #649212)

Utilizator 1994Barbulescu Daniel 1994 Data 15 decembrie 2011 16:46:27
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.94 kb
#include <cstdio>
#include <stack>
#include <vector>
#include <algorithm>
#define N 100005
#include <iostream>
using namespace std;

struct nod_index{
    int Aindex;
    int Lindex;
}nod[N];

vector <int> G[N];
vector <int> C[N];
stack <int> S;
int n,m,nr;
int viz[N];
int index;

void read()
{
    int x,y;
    scanf("%d %d",&n,&m);
    for (int i=1;i<=m;i++)
    {
        scanf("%d %d",&x,&y);
        G[x].push_back(y);
    }
   /* for (int i=1;i<=n;i++)
    {
        printf("%d %d:",G[i].size(),i);
        for (int j=0;j<G[i].size();j++)
            printf("%d ",G[i][j]);
        printf("\n");
    }*/
}

void go(int v)
{
    nod[v].Aindex=nod[v].Lindex=index;
    index++;
    S.push(v);
    viz[v]=1;
    //if (G[v].empty()==false)
    //if (v==8)
     //   printf("%d\n\n",G[v].size());
    for (int i=0;i<G[v].size();i++)
        if (viz[G[v][i]]==0)
        {
            go(G[v][i]);
            nod[v].Lindex=min(nod[v].Lindex,nod[G[v][i]].Lindex);
        }
        else
        if (viz[G[v][i]]!=-1)
            nod[v].Lindex=min(nod[v].Lindex,nod[G[v][i]].Aindex);

    if (nod[v].Lindex==nod[v].Aindex)
    {
        nr++;
        int u;
        do{
            u=S.top();
            viz[u]=-1;
            S.pop();
            C[nr].push_back(u);
        }while (u!=v);
    }
}

void print()
{
    printf("%d\n",nr);
    for (int i=1;i<=nr;i++)
    {
        for (int j=0;j<C[i].size();j++)
            printf("%d ",C[i][j]);
        printf("\n");
    }
}

int main()
{
    freopen("ctc.in","r",stdin);
    freopen("ctc.out","w",stdout);
    read();
    //printf("%d\n\n",G[8].size());
    for (int h=1;h<=n;h++)
        if (viz[h]==0)
            go(h);
    print();
   /* for (int i=1;i<=n;i++)
    {
        printf("%d %d:",G[i].size(),i);
        for (int j=0;j<G[i].size();j++)
            printf("%d ",G[i][j]);
        printf("\n");
    }*/
    return 0;
}