Cod sursa(job #2572265)

Utilizator nTropicManescu Bogdan Constantin nTropic Data 5 martie 2020 12:20:57
Problema Componente tare conexe Scor 60
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <bits/stdc++.h>

using namespace std;

const int len = 200005;
int n, m, cnt;
vector<int> g[len], gt[len], sol[len], v;
bool seen[len];

void dfs1(int node) {
    seen[node] = true;
    for (auto& next : g[node])
        if (!seen[next])
            dfs1(next);
    v.push_back(node);
}

void dfs2(int node) {
    seen[node] = true;
    for (auto& next : gt[node])
        if (!seen[next])
            dfs2(next);
    sol[cnt].push_back(node);
}

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    freopen("ctc.in", "r", stdin);
    freopen("ctc.out", "w", stdout);

    cin >> n >> m;
    for (int i = 1; i <= m; i++) {
        int x, y;
        cin >> x >> y;
        g[x].push_back(y);
        gt[y].push_back(x);
    }

    for (int i = 1; i <= n; i++)
        if (!seen[i])
            dfs1(i);

    for (auto& it : v)
        seen[it] = false;

    while (!v.empty()) {
        int curr = v.back();
        v.pop_back();
        if (!seen[curr]) {
            cnt++;
            dfs2(curr);
        }
    }

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