Cod sursa(job #3233314)

Utilizator MirceaDonciuLicentaLicenta Mircea Donciu MirceaDonciuLicenta Data 2 iunie 2024 23:04:16
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.05 kb
#include <iostream>
#include <vector>
#include <stack>
#include <fstream>
#include <algorithm>

using namespace std;

void dfs1(int node, vector<vector<int>> &adj, vector<bool> &visited, stack<int> &finishStack) {
    visited[node] = true;
    for (int neighbor : adj[node]) {
        if (!visited[neighbor]) {
            dfs1(neighbor, adj, visited, finishStack);
        }
    }
    finishStack.push(node);
}

void dfs2(int node, vector<vector<int>> &transposeAdj, vector<bool> &visited, vector<int> &component) {
    visited[node] = true;
    component.push_back(node);
    for (int neighbor : transposeAdj[node]) {
        if (!visited[neighbor]) {
            dfs2(neighbor, transposeAdj, visited, component);
        }
    }
}

int main() {
    ifstream infile("ctc.in");
    ofstream outfile("ctc.out");

    int N, M;
    infile >> N >> M;

    vector<vector<int>> adj(N + 1);
    vector<vector<int>> transposeAdj(N + 1);

    for (int i = 0; i < M; ++i) {
        int u, v;
        infile >> u >> v;
        adj[u].push_back(v);
        transposeAdj[v].push_back(u);
    }

    stack<int> finishStack;
    vector<bool> visited(N + 1, false);

    // First pass: order vertices by finish time
    for (int i = 1; i <= N; ++i) {
        if (!visited[i]) {
            dfs1(i, adj, visited, finishStack);
        }
    }

    fill(visited.begin(), visited.end(), false);

    // Second pass: find strongly connected components
    vector<vector<int>> scc;
    while (!finishStack.empty()) {
        int node = finishStack.top();
        finishStack.pop();

        if (!visited[node]) {
            vector<int> component;
            dfs2(node, transposeAdj, visited, component);
            scc.push_back(component);
        }
    }

    // Output results
    outfile << scc.size() << endl;
    for (const auto &component : scc) {
        for (int node : component) {
            outfile << node << " ";
        }
        outfile << endl;
    }

    infile.close();
    outfile.close();

    return 0;
}