Cod sursa(job #2662640)

Utilizator mihaifluturFlutur Mihail mihaiflutur Data 24 octombrie 2020 12:02:59
Problema Componente tare conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <fstream>
#include <vector>
std::ifstream fin("ctc.in");
std::ofstream fout("ctc.out");
int n,m,k;
std::vector<std::vector<int>> V,Vt;
std::vector<int> use,cnxt,ts;
void DFS(int N)
{
    use[N]=1;
    for(int i=0; i<(int)V[N].size(); i++)
        if(use[V[N][i]]==0)
            DFS(V[N][i]);
    ts[++k]=N;
}
void DFSt(int N,int cmp)
{
    use[N]=2;
    cnxt[N]=cmp;
    for(int i=0; i<(int)Vt[N].size(); i++)
        if(use[Vt[N][i]]==1)
            DFSt(Vt[N][i],cmp);
}
int main()
{
    int cmp=0;
    fin>>n>>m;
    V.resize(n+2);
    Vt.resize(n+2);
    use.resize(n+2);
    ts.resize(n+2);
    cnxt.resize(n+2);
    for(int i=1; i<=m; i++)
    {
        int x,y;
        fin>>x>>y;
        V[x].push_back(y);
        Vt[y].push_back(x);
    }
    for(int i=1; i<=n; i++)
        if(!use[i])
            DFS(i);
    for(int i=1; i<=n; i++)
        if(use[ts[n-i+1]]==1)
            DFSt(i,++cmp);
    fout<<cmp<<"\n";
    for(int i=1; i<=cmp; i++)
    {
        for(int j=1; j<=n; j++)
            if(cnxt[j]==i)
                fout<<j<<" ";
        fout<<"\n";
    }
    return 0;
}