Cod sursa(job #382788)

Utilizator cristikIvan Cristian cristik Data 14 ianuarie 2010 18:59:07
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.09 kb
#include <stdio.h>
#include <vector>
#include <algorithm>
#define max 100010
using namespace std;
vector<int> g[max],comp[max];
int stack[max],low[max],ind[max],n,m,i,j,scc,timp,top;
char s[max];
void dfs(int v)
{
    low[v]=ind[v]=++timp;
    stack[++top]=v;
    for(int i=0; i<g[v].size(); ++i)
    if(!s[g[v][i]])
    {
        if(!ind[g[v][i]]) dfs(g[v][i]);
        low[v]=min(low[v],low[g[v][i]]);
    }
    if(low[v]==ind[v])
    {
        scc++;
        while(stack[top]!=v)
        {
            s[stack[top]]=1;
            comp[scc].push_back(stack[top--]);
        }
        comp[scc].push_back(v);
        s[v]=1;
        top--;
    }
}
int main()
{
    freopen("ctc.in","r",stdin);
    freopen("ctc.out","w",stdout);
    scanf("%d%d",&n,&m);
    for(; m>0; m--)
    {
        scanf("%d%d",&i,&j);
        g[i].push_back(j);
    }
    for(i=1; i<=n; i++)
     if(!ind[i]) dfs(i);
    printf("%d\n",scc);
    for(i=1; i<=scc; i++)
    {
        for(j=0; j<comp[i].size(); j++)
         printf("%d ",comp[i][j]);
        printf("\n");
    }
    return 0;
}