Cod sursa(job #2862660)

Utilizator sandupetrascoPetrasco Sandu sandupetrasco Data 5 martie 2022 17:50:25
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
# include <bits/stdc++.h>
#define N 100100
using namespace std;

int n, m, k, x, y, cnt;
vector < int > V[N], INV[N], R[N];
stack < int > S;
bitset< N > vis;

void dfs(int x) {
    vis[x] = true;

    for (auto it : V[x]) {
        if (!vis[it]) {
            dfs(it);
        }
    }
    
    S.push(x);
}

void dfsINV(int x) {
    vis[x] = true;
    R[cnt].push_back(x);

    for (auto it : INV[x]) {
        if (!vis[it]) {
            dfsINV(it);
        }
    }

}

int main() {
    ifstream cin("ctc.in");
    ofstream cout("ctc.out");

    cin >> n >> m;

    for (int i = 1; i <= m; i++) {
        cin >> x >> y;

        V[x].push_back(y);
        INV[y].push_back(x);
    }

    for (int i = 1; i <= n; i++) {
        if (!vis[i]) {
            dfs(i);
        }
    }

    vis.reset();

    while (!S.empty()) {
        int node = S.top();
        S.pop();

        if (!vis[node]) {
            dfsINV(node);
            ++cnt;
        }
    }

    cout << cnt << "\n";
    for (int i = 0; i < cnt; i++) {
        for (auto it : R[i]) {
            cout << it << " ";
        }

        cout << "\n";
    }
    
    return 0;
}