Cod sursa(job #2870752)

Utilizator BorodiBorodi Bogdan Borodi Data 12 martie 2022 15:42:32
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <fstream>
#include <string>
#include <cstring>
#include <map>
#include <algorithm>
#include <stack>
#include <vector>
#include <queue>
#include <bitset>
#define Nmax 100001
using namespace std;

ifstream fin("ctc.in");
ofstream fout("ctc.out");

const int oo = 1 << 28;
typedef vector < int > VI;

int n, m, ct, x, y;
bool F[Nmax];
VI V[Nmax], VT[Nmax], CTC[Nmax];
stack <int> S;

void TopSort(int vertex){
    F[vertex] = 1;

    for(int new_vertex : V[vertex])
        if(!F[new_vertex])
            TopSort(new_vertex);
    
    S.push(vertex);    
}
void DFS(int vertex){
    F[vertex] = 1;
    CTC[ct].push_back(vertex);

    for(int new_vertex : VT[vertex])
        if(!F[new_vertex])
            DFS(new_vertex);
}
int main() {
    fin >> n >> m;

    for(int i = 1; i <= m; ++i){
        fin >> x >> y;
        V[x].push_back(y);
        VT[y].push_back(x);
    }

    for(int i = 1; i <= n; ++i)
        if(!F[i])
            TopSort(i);

    memset(F, 0, sizeof(F));

    while(S.size()){
        int vertex = S.top();

        if(!F[vertex])
            ct++,
            DFS(vertex);
        
        S.pop();
    }

    fout << ct << '\n';

    for(int i = 1; i <= ct; ++i, fout << "\n")
        for(int j : CTC[i])
            fout << j << " ";

    return 0;
}