Cod sursa(job #916085)

Utilizator camelia_popescuPopescu Camelia camelia_popescu Data 15 martie 2013 19:46:31
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

const int N=200000;

int n,m,nc,blocat[N],nr;
vector <int> s[N],p[N],c[N];
bool viz[N],viz2[N];


ifstream in("ctc.in");
ofstream out("ctc.out");

void citire()
{
    int x, y,i;
    in>>n>>m;
    for(i=1;i<=m;i++)
    {
        in>>x>>y;
        s[x].push_back(y);
        p[y].push_back(x);
    }
}

void dfs(int x)
{
    viz[x]=true;
    int y;
    for(size_t i=0;i<s[x].size(); i++)
    {
        y=s[x][i];
        if(!viz[y]) dfs(y);
    }
    blocat[++nr]=x;
}

void dfs2 (int x)
{
    viz2[x]=true;
    c[nc].push_back(x);
    int y;
    for(size_t i=0;i<p[x].size();i++)
    {
        y=p[x][i];
        if(!viz2[y]) dfs2(y);
    }
}

int main()
{
    int j,x,i;
    citire();
    for(i=1;i<=n;i++)
        if(!viz[i])
            dfs(i);
    for(i=n;i>=1;i--)
    {
        x=blocat[i];
        if(!viz2[x])
        {
            ++nc;
            dfs2(x);
            //out<<"\n";
        }
    }
    out<<nc<<"\n";
    for(i=1;i<=nc;i++)
    {
        for(j=0;j<c[i].size();j++)
           out<<c[i][j]<<" ";
        out<<"\n";
    }
    return 0;
}