Cod sursa(job #2428522)

Utilizator baltoi.teodorTeodor Baltoi baltoi.teodor Data 5 iunie 2019 17:35:15
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.09 kb
#include <bits/stdc++.h>
#define NMAX 100006
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");
vector <int> g[NMAX];
vector <int> gt[NMAX];
int N,M;
int postord[NMAX];
int k;
bool viz[NMAX];
vector<int>ctc[NMAX];
void dfsps(int x)
{
    viz[x]=1;
    for(vector<int>::iterator i=g[x].begin();i!=g[x].end();++i)
        if(!viz[*i]) dfsps(*i);
    postord[++k]=x;
}
int nr,Nr=0;
void dfs(int x)
{
    viz[x]=1;
    ctc[Nr].push_back(x);
    for(vector<int>::iterator i=gt[x].begin();i!=gt[x].end();++i)
        if(!viz[*i]) dfs(*i);
}
int main()
{
    int j,i,x,y;
    fin>>N>>M;
    for(i=1;i<=M;++i)
    {
        fin>>x>>y;
        g[x].push_back(y);
        gt[y].push_back(x);
    }
    for(i=1;i<=N;++i)
        if(viz[i]==0) dfsps(i);
    for(i=1;i<=N;++i) viz[i]=0;
    for(i=N;i>=1;i--)
    if(!viz[postord[i]]) {
        Nr++;
        nr=0;
        dfs(postord[i]);
    }
    fout<<Nr<<"\n";
    for(i=1;i<=Nr;++i)
    {
        for(j=0;j<ctc[i].size();++j)
            fout<<ctc[i][j]<<" ";
        fout<<"\n";
    }
    return 0;
}