Cod sursa(job #3340299)

Utilizator Warrior.exeZgorcea Mihai-Alexandru Warrior.exe Data 13 februarie 2026 16:36:18
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.24 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;


ifstream f("ctc.in");
ofstream g("ctc.out");

const int NMAX = 100000+1;

int N,M,nrc;

vector<int>G[NMAX],GT[NMAX],CTC[NMAX],Post;

bool viz[NMAX];

void citire(){
    int x,y;
    f >> N >> M;
    while(M--){
        f >> x >> y;
        G[x].push_back(y);
        GT[y].push_back(x);
    }
}

void dfs(int vf){
    viz[vf] = 1; /// +
    for(int x : G[vf]){
        if(viz[x] == 0){
            dfs(x);
        }
    }
    Post.push_back(vf);
}

void dfsGT(int vf){
    viz[vf] = 0;///-
    CTC[nrc].push_back(vf);
    for(int x:GT[vf]){
        if(viz[x] == 1){
            dfsGT(x);
        }
    }
}

void componente(){
    int i;
    for(i=1;i<=N;i++){
        if(viz[i] ==0){
            dfs(i);
        }
    }
    for(i = Post.size()-1;i>=0;i--){
        if(viz[Post[i]] == 1){
            nrc++;
            dfsGT(Post[i]);
        }
    }
}

void afisare(){
    g<<nrc<<'\n';
    for(int i=1;i<=nrc;i++){
        for(int x:CTC[i]){
            g<<x<<" ";
        }
        g<<'\n';
    }
}

int main(){
    citire();
    componente();
    afisare();
    f.close();
    g.close();
    return 0;
}