Cod sursa(job #2704718)

Utilizator daniel.lazurcaLazurca Daniel-Vasile daniel.lazurca Data 11 februarie 2021 08:52:22
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <bits/stdc++.h>

using namespace std;
ifstream f("ctc.in");
ofstream g("ctc.out");
#define Nmax 100005
int N, M, beenThere[Nmax], NrCTC;
vector <int> G[Nmax], GT[Nmax], result[Nmax];
stack <int> S;
int DFS(int Nod)
{
    beenThere[Nod]=1;
    for(int i=0; i<G[Nod].size(); i++)
    {
        int Vecin=G[Nod][i];
        if(!beenThere[Vecin])
            DFS(Vecin);
    }
    S.push(Nod);
}
int DFS_T(int Nod)
{
    beenThere[Nod]=2;
    result[NrCTC].push_back(Nod);
    for(int i=0; i<GT[Nod].size(); i++)
    {
        int Vecin=GT[Nod][i];
        if(beenThere[Vecin]==1)
            DFS_T(Vecin);
    }

}
void Solve()
{
    for(int i=1; i<=N; i++)
        if(!beenThere[i])
            DFS(i);
    while(!S.empty())
    {
        int Nod=S.top();
        if(beenThere[Nod]==1)
        {
            NrCTC++;
            DFS_T(Nod);
        }
        S.pop();
    }
}
void print()
{
    g<<NrCTC<<'\n';
    for(int i=1; i<=NrCTC; i++)
    {
        for(int j=0; j<result[i].size(); j++)
            {
                int sol=result[i][j];
                g<<sol<<" ";
            }
            g<<'\n';
    }
}
int main()
{
    f>>N>>M;
    for(int i=1; i<=M; i++)
    {
        int x,y;
        f>>x>>y;
        G[x].push_back(y);
        GT[y].push_back(x);
    }
    Solve();
    print();
    return 0;
}