Cod sursa(job #1335909)

Utilizator andreismara97Smarandoiu Andrei andreismara97 Data 6 februarie 2015 01:43:14
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 kb
#include<fstream>
#include<vector>
using namespace std;
ifstream in("ctc.in");
ofstream out("ctc.out");

#define Nmax 100005

vector <int> lista[Nmax], comp[Nmax], transp[Nmax];
int N, M, viz[Nmax]={0}, post[Nmax], ct=0;

void citire()
{
    int x,y;
    in>>N>>M;
    for(int i=1;i<=M;i++)
    {
        in>>x>>y;
        lista[x].push_back(y);
        transp[y].push_back(x);
    }
}


void Dfs( int nod)
{
    viz[nod]=1;
    for(int i=0; i<lista[nod].size(); i++)
        if(viz[lista[nod][i]] == 0)
            Dfs(lista[nod][i]);
    post[++ct]=nod;
}


void TDfs( int nod)
{
    viz[nod]=0;
    comp[ct].push_back(nod);
    for(int i=0; i<transp[nod].size(); i++)
        if(viz[transp[nod][i]] == 1)
            TDfs(transp[nod][i]);
}

int main ()
{
    citire();
    for(int i=1; i<=N; i++)
        if(viz[i] == 0)
            Dfs(i);

    ct=0;
    for(int i=N; i>=1;i--)
        if( viz[ post[i]] ==1)
        {
            ct++;
            TDfs(post[i]);
        }

    out<<ct<<'\n';
    for(int i=1; i<=ct; i++)
    {
        for(int j=0; j<comp[i].size(); j++)
            out<<comp[i][j]<<' ';
        out<<'\n';
    }

    return 0;
}