Cod sursa(job #2662672)

Utilizator mihaifluturFlutur Mihail mihaiflutur Data 24 octombrie 2020 12:25:27
Problema Componente tare conexe Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 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> cnxt,ts;
std::vector<bool> use;
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]=1;
    cnxt[N]=cmp;
    for(int i=0; i<(int)Vt[N].size(); i++)
        if(use[Vt[N][i]]==0)
            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++)use[i]=0;
    for(int i=n; i>=1; i--)
        if(!use[ts[i]])
            DFSt(ts[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;
}