Cod sursa(job #3136280)

Utilizator BetJohn000Ioan Benescu BetJohn000 Data 5 iunie 2023 20:27:14
Problema Componente tare conexe Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.59 kb
#include <iostream>
#include <vector>
#include <queue>
#include <fstream>
#include <stack>
using namespace std;

ifstream fin("ctc.in");
ofstream fout("ctc.out");
#define NMax 100005
vector <int> G[NMax], GT[NMax];
stack <int> S;
int N,M,NrCTC;
int beenThere[NMax];
vector <int> result[100];
void Read()
{
    fin>>N>>M;
    for(int i=1;i<=M;i++)
    {
        int x,y;
        fin>>x>>y;
        G[x].push_back(y);
        GT[y].push_back(x);
    }
}
void DFS(int Nod)
{
    beenThere[Nod] = 1;
    //Zona 1
    for(unsigned int i = 0; i<G[Nod].size();i++)
    {
        //Zona 2
        int Vecin = G[Nod][i];
        if(!beenThere[Vecin])
            DFS(Vecin);
        //Zona 3
    }
    S.push(Nod);
    //Zona 4
}
void DFS_T(int Nod){
    beenThere[Nod] = 2;
    result[NrCTC].push_back(Nod);
    //Zona 1
    for(unsigned int i = 0; i<GT[Nod].size();i++)
    {
        //Zona 2
        int Vecin = GT[Nod][i];
        if(beenThere[Vecin]==1)
            DFS_T(Vecin);
        //Zona 3
    }
    //Zona 4
}
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()
{
    fout<<NrCTC<<"\n";
    for(int i=1;i<=NrCTC;i++)
    {
        for(unsigned int j = 0;j<result[i].size();j++)
            fout<<result[i][j]<<" ";
        fout<<"\n";
    }
}

int main()
{
    Read();
    Solve();
    Print();
    return 0;
}