Cod sursa(job #3271386)

Utilizator andu9andu nita andu9 Data 25 ianuarie 2025 21:59:48
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.12 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>

const int nMax = 1e5;

void DFS(std::vector<std::vector<int>>& graph, std::bitset<nMax>& vis,
         std::vector<int>& time, int currNode) {
    vis[currNode] = true;
    for (int& next : graph[currNode]) {
        if (vis[next] == false) {
            DFS(graph, vis, time, next);
        }
    }
    time.emplace_back(currNode);
}

void transposeDFS(std::vector<std::vector<int>>& graph, std::vector<int>& scc,
         int currNode, int currSCC) {
    scc[currNode] = currSCC;
    for (int& next : graph[currNode]) {
        if (scc[next] == -1) {
            transposeDFS(graph, scc, next, currSCC);
        }
    }
}

int main() {
    std::ifstream fin("ctc.in");
    std::ofstream fout("ctc.out");

    int n, m; fin >> n >> m;
    std::vector<std::vector<int>> graph(n, std::vector<int>());
    std::vector<std::vector<int>> transpose(n, std::vector<int>());
    for (int i = 0; i < m; i += 1) {
        int u, v; fin >> u >> v; u -= 1, v -= 1;
        graph[u].emplace_back(v);
        transpose[v].emplace_back(u);
    }

    std::vector<int> time;
    std::bitset<nMax> vis;
    for (int i = 0; i < n; i += 1) {
        if (vis[i] == false) {
            DFS(graph, vis, time, i);
        }
    }

    int noSCC = 0; vis.reset();
    std::vector<int> scc(n, -1);
    for (auto it = time.rbegin(); it != time.rend(); ++it) {
        int node = *it;
        if (scc[node] == -1) {
            transposeDFS(transpose, scc, node, noSCC);
            noSCC += 1;
        }
    }

    std::vector<std::vector<int>> components(noSCC, std::vector<int>());
    for (int i = 0; i < n; i += 1) {
        components[scc[i]].emplace_back(i);
    }

    fout << noSCC << '\n';
    for (int i = 0; i < noSCC; i += 1) {
        for (int j = 0; j < (int) components[i].size(); j += 1) {
            fout << components[i][j] + 1 << ' ';
        }
        fout << '\n';
    }


    components.clear();
    time.clear(), scc.clear();
    graph.clear(), transpose.clear();
    fin.close(), fout.close();
    return 0;
}