Cod sursa(job #1344427)

Utilizator ThomasFMI Suditu Thomas Thomas Data 16 februarie 2015 18:45:57
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.98 kb
#include <fstream>
#include <vector>
using namespace std;

#define NMax 100005

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

int n,m;
vector<int> v[NMax], w[NMax];
bool viz[NMax];
int postordine[NMax];
int nr;

int nrsol;
vector<int> sol[NMax];

void DFS(int x)
{
    viz[x] = true;
    for(int i=0;i<v[x].size();++i) if(!viz[v[x][i]]) DFS(v[x][i]);
    postordine[++nr] = x;
}

void DFST(int x)
{
    viz[x] = false;
    for(int i=0;i<w[x].size();++i) if(viz[w[x][i]]) DFST(w[x][i]);
    sol[nrsol].push_back(x);
}

int main()
{
    int i,j,a,b;

    f>>n>>m;
    while(m--)
    {
        f>>a>>b;
        v[a].push_back(b);
        w[b].push_back(a);
    }

    for(i=1;i<=n;++i) if(!viz[i]) DFS(i);
    for(i=n;i>=1;--i) if(viz[postordine[i]]) {++nrsol; DFST(postordine[i]);}

    g<<nrsol<<"\n";
    for(i=1;i<=nrsol;++i)
    {
        for(j=0;j<sol[i].size();++j) g<<sol[i][j]<<" "; g<<"\n";
    }

    f.close();
    g.close();
    return 0;
}