Cod sursa(job #1922634)

Utilizator mariapascuMaria Pascu mariapascu Data 10 martie 2017 18:10:01
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.48 kb
#include <fstream>
#include <vector>
#include <stack>
using namespace std;

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

int n, m, nrc, idx;
vector<vector<int>> G, CC;
vector<int> L, Index, C;
vector<bool> InStack;
stack<int> Stk;

void Read();
void Tarjan(int x);
void Write();

int main() {
    Read();
    for (int i = 1; i <= n; i++)
        if (Index[i] == 0) Tarjan(i);
    Write();
    fin.close();
    fout.close();
    return 0;
}

void Tarjan(int x) {
    idx++;
    L[x] = Index[x] = idx;
    Stk.push(x);
    InStack[x] = true;
    for (const auto & y : G[x])
        if (Index[y] == 0) {
            Tarjan(y);
            L[x] = min(L[y], L[x]);
        }
        else if (InStack[y])
            L[x] = min(L[x], Index[y]);
    if (L[x] == Index[x]) {
        nrc++;
        C.clear();
        int nod;
        do {
            nod = Stk.top();
            Stk.pop();
            C.push_back(nod);
            InStack[nod] = false;
        }
        while (nod != x);
        CC.push_back(C);
    }
 }

void Write() {
    fout << nrc << '\n';
    for (const auto & c : CC) {
        for (const auto & x : c)
            fout << x << ' ';
        fout << '\n';
    }
}

void Read() {
    fin >> n >> m;
    G = vector<vector<int>>(n + 1);
    L = Index = vector<int>(n + 1);
    InStack = vector<bool>(n + 1);
    int x, y;
    for (int i = 1; i <= m; i++) {
        fin >> x >> y;
        G[x].push_back(y);
    }
}