Cod sursa(job #1895832)

Utilizator roxannemafteiuMafteiu-Scai Roxana roxannemafteiu Data 28 februarie 2017 11:20:10
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.49 kb
#include <bits/stdc++.h>

using namespace std;

const int N_MAX = 1e5 + 5;

int n, m, strongComponents;
vector <int> g[N_MAX], t[N_MAX], solution[N_MAX];
bitset <N_MAX> visited;
stack <int> st;

void read() {
    ifstream fin("ctc.in");

    fin >> n >> m;
    while (m--) {
        int x, y;
        fin >> x >> y;
        g[x].emplace_back(y);
        t[y].emplace_back(x);
    }

    fin.close();
}

void dfs_g(int node) {
    visited.set(node);
    for (const auto &son : g[node]) {
        if (!visited[son]) {
            dfs_g(son);
        }
    }

    st.emplace(node);
}

void dfs_t(int node) {
    visited.reset(node);
    solution[strongComponents].emplace_back(node);
    for (const auto &son : t[node]) {
        if (visited[son]) {
            dfs_t(son);
        }
    }
}

void solve() {
    for (int node = 1; node <= n; ++node) {
        if (!visited[node]) {
            dfs_g(node);
        }
    }

    while (!st.empty()) {
        int node = st.top();
        if (visited[node]) {
            ++strongComponents;
            dfs_t(node);
        }

        st.pop();
    }
}

void write() {
    ofstream fout("ctc.out");

    fout << strongComponents << '\n';
    for (int i = 1; i <= strongComponents; ++i) {
        for (const auto &node : solution[i]) {
            fout << node << ' ';
        }

        fout << '\n';
    }

    fout.close();
}

int main() {
    read();
    solve();
    write();
    return 0;
}