Cod sursa(job #2090742)

Utilizator PaulTPaul Tirlisan PaulT Data 18 decembrie 2017 17:57:27
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.57 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <stack>
using namespace std;

using VI = vector<int>;
using VVI = vector<VI>;
using VB = vector<bool>;

VVI G, ctc;
VI niv, L, c;
VB inStack;
stack<int> stk;
int n, m, nv, tp;

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

int main()
{
    ReadGraph();
    for (int x = 1; x <= n; x++)
        if (!niv[x])
        {
            nv = 0;
            Tarjan(x);
        }
    Write();
}

void Tarjan(int x)
{
    niv[x] = L[x] = ++nv;
    stk.push(x);
    inStack[x] = true;
    for (const int& y : G[x])
        if (!niv[y])
        {
            Tarjan(y);
            L[x] = min(L[x], L[y]);
        }
        else
            if (inStack[y])
                L[x] = min(L[x], niv[y]);
    if (L[x] == niv[x])
    {
        c.clear();
        while (!stk.empty())
        {
            tp = stk.top();
            stk.pop();
            inStack[tp] = false;
            c.push_back(tp);
            if (tp == x)
                break;
        }
        ctc.push_back(c);
    }
}

void Write()
{
    ofstream fout("ctc.out");
    fout << ctc.size() << '\n';
    for (VI& c : ctc)
    {
        for (const int& x : c)
            fout << x << ' ';
        fout << '\n';
    }
    fout.close();
}

void ReadGraph()
{
    ifstream fin("ctc.in");
    fin >> n >> m;
    G = VVI(n + 1);
    niv = L = VI(n + 1);
    inStack = VB(n + 1);
    int x, y;
    while (m--)
    {
        fin >> x >> y;
        G[x].push_back(y);
    }
    fin.close();
}