Cod sursa(job #2683129)

Utilizator bogdan62003isache bogdan bogdan62003 Data 10 decembrie 2020 15:50:17
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <bits/stdc++.h>



using namespace std;



#define NM 100005



int n,m,postord[NM], t, viz[NM], k;
vector<int> G[NM], GT[NM], ctc[NM];
ifstream fin("ctc.in");
ofstream fout("ctc.out");
void DFS(int x)
{
    int i, w;



    viz[x] = 1;



    for (i = 0;i< G[x].size();i++)
        {
            w=G[x][i];
            if (!viz[w])
                DFS(w);
        }
t++;
postord[t] = x;
}



void DFST(int x)
{
    int i, w;



    viz[x] = 1;
    ctc[k].push_back(x);
    for (i = 0;i<GT[x].size(); i++)
    {
        w=GT[x][i];
        if (!viz[w])
            DFST(w);
    }



}



int main()
{
    int i,j, x, y;
    fin>>n>>m;
    for (i=1;i<=m;i++)
    {
        fin>>x>>y;
        G[x].push_back(y);///liste de adiacentaale grafului dat G
        GT[y].push_back(x);///liste de adiacentaale grafului dat GT
    }
///pasul 1
    for (i = 1; i <= n; i++)
        if (!viz[i])
            DFS(i);



///resetam vectorul viz
    for(i=1;i<=n;i++)
        viz[i]=0;



    k=0;
///parcurgem in in sens invers vectorul postord
    for (i = n; i>=1; i--)
        if (!viz[postord[i]])
        {
            k++;
            DFST(postord[i]);
        }



    fout<<k<<'\n';
    for (i = 1; i <= k; i++)
    {
        sort(ctc[i].begin(),ctc[i].end());
        for (j=0; j < ctc[i].size(); j++)
            fout<<ctc[i][j]<<' ';
        fout<<'\n';
    }



    return 0;
}