Cod sursa(job #2913254)

Utilizator Frant_IoanaFrant Ioana Frant_Ioana Data 13 iulie 2022 15:25:00
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 kb
#include <bits/stdc++.h>
using namespace std;

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

int n, m, x, y, beenthere[100001], cnt;
vector<int> g[100001], gt[100001], CTC[100001];
stack<int> s;

void dfs1(int nod){

    beenthere[nod] = 1;
    for(auto i : g[nod])
        if(!beenthere[i])
            dfs1(i);
    
    s.push(nod);
}

void dfs2(int nod){

    beenthere[nod] = 2;
    CTC[cnt].push_back(nod);
    for(auto i : gt[nod])
        if(beenthere[i] == 1)
            dfs2(i);
}

int main(){

    fin >> n >> m;
    for(int i = 1; i <= m; i++)
        fin >> x >> y, g[x].push_back(y), gt[y].push_back(x);
    
    for(int i = 1; i <= n; i++)
        if(!beenthere[i])
            dfs1(i);
    
    while(!s.empty()){
        int nod = s.top();
        if(beenthere[nod] == 1)
            cnt++, dfs2(nod);
        s.pop();
    }

    fout << cnt << '\n';
    for(int i = 1; i <= cnt; i++){
        for(int j : CTC[i])
            fout << j << ' ';
        fout << '\n';
    }
}