Cod sursa(job #2663870)

Utilizator CostinteoGrigore Costin Teodor Costinteo Data 27 octombrie 2020 15:31:29
Problema Componente tare conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.78 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>

#define NMAX 100005

std::vector <std::vector<int>> adj(NMAX), sccList;
std::vector <int> idx, lowlink, conex, onStack;
std::stack <int> stack;
int atIDX = 0;

void read(std::vector <std::vector<int>> adj, int &n) {
    std::ifstream f("ctc.in");
    f >> n;;
    int edges;
    f >> edges;
    for (int i = 0; i < edges; i++) {
        int x, y;
        f >> x >> y;
        adj[x-1].push_back(y-1);
    }
    f.close();
}

void print(const std::vector <std::vector<int>> sccList) {
    std::ofstream g("ctc.out");
    g << sccList.size() << '\n';
    for (int i = 0; i < sccList.size(); i++) {
        for (int j = 0; j < sccList[i].size(); j++) {
            g << sccList[i][j] + 1 << " ";
        }
        g << '\n';
    }
    g.close();
}

void tarjan(int x, std::vector <std::vector<int>> adj) {
    idx[x] = lowlink[x] = atIDX;
    stack.push(x);
    onStack[x] = 1;
    atIDX++;
    for (int i = 0; i < adj[i].size(); i++) {
        if (idx[i] == -1) {
            tarjan(i, adj);
            lowlink[x] = std::min(lowlink[x], lowlink[i]);
        } else if (onStack[i] == 1) {
            lowlink[x] = std::min(lowlink[x], lowlink[i]);
        }
    }

    if (idx[x] == lowlink[x]) {
        conex.clear();
        int node;
        do {
            conex.push_back(node = stack.top());
            stack.pop();
            onStack[node] = 0;
        } while (node != x);

        sccList.push_back(conex);
    }
}

int main() {
    int n;
    read(adj, n);

    idx.resize(n);
    lowlink.resize(n);
    onStack.resize(n);
    idx.assign(n, -1);
    onStack.assign(n, 0);

    for (int i = 0; i < n; i++) {
        if (idx[i] == -1) {
            tarjan(i, adj);
        }
    }

    print(sccList);
    return 0;
}