Cod sursa(job #2152796)

Utilizator marcdariaDaria Marc marcdaria Data 5 martie 2018 19:59:53
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.94 kb
// Det Comp Tare Conexe
// Alg. lui Tarjan
// O(m)
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;

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

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

int n, m;
VVI G;      // graful
VI  niv;    // niv[x] = timpul de descoperire a nodului x (index)
VI L;
VB inStack;
int idx;    // timpul curent
VVI cc;     // retine comp tare conexe
VI c;       // comp tare conexa curenta
stack<int> stk;

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

int main()
{
    ReadGraph();
    StronglyConnectedComp();
    Write();
    fin.close();
    fout.close();
}

void StronglyConnectedComp()
{
    for (int x = 1; x <= n; ++x) // O(m)
        if (niv[x] == 0)
            Tarjan(x);
}

void Tarjan(int x)
{
    niv[x] = L[x] = ++idx;
    stk.push(x); inStack[x] = true;

    for (const int& y : G[x])
        if (!niv[y])  // tree edge
        {
            Tarjan(y);
            L[x] = min(L[x], L[y]);
        }
        else
            if (inStack[y]) // daca e in stiva, atunci e stramos => back edge
                L[x] = min(L[x], niv[y]);

    if (L[x] == niv[x]) // x e reprezentantul unei C.T.C
    {
        c.clear();
        while (!stk.empty())
        {
            int z = stk.top();
            stk.pop();
            inStack[z] = false;
            c.push_back(z);
            if (z == x)
                break;
        }
        cc.push_back(c);
    }
}


void ReadGraph()
{
    fin >> n >> m;
    G = VVI(n + 1);
    L = niv = VI(n + 1);

    inStack = VB(n + 1);
    int x, y;
    while (m--)
    {
        fin >> x >> y;
        G[x].push_back(y);
    }
}

void Write()
{
    fout << cc.size() << '\n';
    for (auto& c : cc)
    {
        for (auto& x : c)
            fout << x << ' ';
        fout << '\n';
    }
}