Cod sursa(job #2224770)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 25 iulie 2018 00:21:53
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
#include <bits/stdc++.h>

using namespace std;

void dfs(const vector<vector<int>>& graph, int node, vector<bool>& visited, vector<int>& topSort){
    visited[node] = true;

    for (int x: graph[node])
        if (!visited[x])
            dfs(graph, x, visited, topSort);

    topSort.push_back(node);
}

void dfsT(const vector<vector<int>>& graphT, int node, vector<bool>& visited, vector<int>& comp){
    visited[node] = false;

    for (int x: graphT[node])
        if (visited[x])
            dfsT(graphT, x, visited, comp);

    comp.push_back(node);
}

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

    ios_base::sync_with_stdio(false);

    int N, M;
    cin >> N >> M;

    vector<vector<int>> graph(N);
    vector<vector<int>> graphT(N);

    while (M--){
        int x, y;
        cin >> x >> y;
        x--; y--;

        graph[x].push_back(y);
        graphT[y].push_back(x);
    }

    vector<bool> visited(N, false);
    vector<int> topSort;

    for (int i = 0; i < N; i++)
        if (!visited[i])
            dfs(graph, i, visited, topSort);

    reverse(topSort.begin(), topSort.end());

    vector<vector<int>> comps;

    for (int x: topSort)
        if (visited[x]) {
            comps.push_back({});
            dfsT(graphT, x, visited, comps[comps.size() - 1]);
        }

    cout << comps.size() << "\n";

    for (auto x: comps){
        for (auto y: x)
            cout << y + 1 << " ";
        cout << "\n";
    }

    return 0;
}