Cod sursa(job #2713379)

Utilizator vnedelcuVictor Andrei Nedelcu vnedelcu Data 27 februarie 2021 20:17:54
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.06 kb
#include <stdio.h>
#include <vector>
#include <stack>

using namespace std;

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

void dfs_transposed(
    int node, vector<vector<int > > & transposed_graph,
    vector<int> & visited, vector<vector<int> > & components, const int components_pos
) {
    visited[node] = true;
    components[components_pos].push_back(node);
    for (int neighbor: transposed_graph[node]) {
        if (!visited[neighbor]) {
            dfs_transposed(neighbor, transposed_graph, visited, components, components_pos);
        }
    }
}

int main() {
    FILE * f;
    int n, m, x, y;

    f = fopen("ctc.in", "r");
    fscanf(f, "%d%d", &n, &m);
    vector<vector<int> > graph(n);
    vector<vector<int> > transposed_graph(n);
    for (int i = 0; i < m; ++i) {
        fscanf(f, "%d%d", &x, &y);
        --x;
        --y;
        graph[x].push_back(y);
        transposed_graph[y].push_back(x);
    }
    fclose(f);

    vector<int> visited(n, false);
    stack<int> stack;
    for (int i = 0; i < n; ++i) {
        if (!visited[i]) {
            dfs(i, graph, visited, stack);
        }
    }

    visited.assign(n, false);
    vector<vector<int> > components(n);
    int no_components = 0;
    while (!stack.empty()) {
        int node = stack.top();
        stack.pop();
        if (!visited[node]) {
            ++no_components;
            dfs_transposed(node, transposed_graph, visited, components, no_components);
        }
    }

    f = fopen("ctc.out", "w");
    fprintf(f, "%d\n", no_components);
    for (int i = 0; i < n; ++i) {
        if (components[i].size()) {
            for (int node: components[i]) {
                fprintf(f, "%d ", node + 1);
            }
            fprintf(f, "\n");
        }
    }
    fclose(f);

    return 0;
}