Cod sursa(job #3229913)

Utilizator ALEXbrPopa Ioan Alexandru ALEXbr Data 17 mai 2024 23:50:43
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.36 kb
#include <bits/stdc++.h>
using namespace std;

struct NodeStack {
    std::vector<int> stack;
    std::vector<bool> inStack;

    explicit NodeStack(int n) {
        inStack = vector<bool>(n);
    }

    void push(int node) {
        stack.push_back(node);
        inStack[node] = true;
    }

    int pop() {
        int node = stack.back();
        stack.pop_back();
        inStack[node] = false;

        return node;
    }
};

void dfs(int node, int &timestamp, const vector<vector<int>> &dests, vector<int> &parent, vector<int> &found, vector<int> &lowLink, NodeStack &nodeStack, vector<vector<int>> &strongCons) {
    found[node] = ++timestamp;
    lowLink[node] = found[node];
    nodeStack.push(node);

    for (const int &dst : dests[node]) {
        if (parent[dst] != -1) {
            if (nodeStack.inStack[dst]) {
                lowLink[node] = min(lowLink[node], found[dst]);
            }

            continue;
        }

        parent[dst] = node;

        dfs(dst, timestamp, dests, parent, found, lowLink, nodeStack, strongCons);

        lowLink[node] = min(lowLink[node], lowLink[dst]);
    }

    if (lowLink[node] == found[node]) {
        vector<int> newStrongCon;

        int newNode = -1;
        while (newNode != node) {
            newNode = nodeStack.pop();
            newStrongCon.push_back(newNode);
        }

        strongCons.push_back(newStrongCon);
    }
}

int main() {
    ios::sync_with_stdio(false);

    ifstream fin("ctc.in");
    ofstream fout("ctc.out");

    int n, m;
    fin >> n >> m;

    vector<vector<int>> dests(n, vector<int>());

    for (int i = 0; i < m; i++) {
        int src, dst;
        fin >> src >> dst;

        src--;
        dst--;

        dests[src].push_back(dst);
    }

    vector<int> parent(n, -1), found(n, INT_MAX), lowLink(n, INT_MAX);
    vector<vector<int>> strongCons;

    NodeStack nodeStack(n);
    int timestamp = 0;

    for (int i = 0; i < n; i++) {
        if (parent[i] != -1) {
            continue;
        }

        parent[i] = i;
        dfs(i, timestamp, dests, parent, found, lowLink, nodeStack, strongCons);
    }

    fout << strongCons.size() << '\n';
    for (const auto &strongCon : strongCons) {
        for (int i = 0; i < strongCon.size(); i++) {
            if (i != 0) {
                fout << ' ';
            }
            fout << strongCon[i] + 1;
        }
        fout << '\n';
    }

    return 0;
}