Cod sursa(job #2376705)

Utilizator PaulTPaul Tirlisan PaulT Data 8 martie 2019 17:10:10
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;

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

int n, m;
stack<int> stk;
VVI G, Gt, ctc;
VI c;
VB v;

void Read();
void Kosaraju();
void Df(int x);
void DfT(int x);
void Write();

int main()
{
    Read();
    Kosaraju();
    Write();
}

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

void Kosaraju()
{
    for (int x = 1; x <= n; x++)
        if (!v[x])
            Df(x);
    v = VB(n + 1);
    int x;
    while (!stk.empty())
    {
        x = stk.top();
        stk.pop();
        if (v[x])
            continue;
        c.clear();
        DfT(x);
        ctc.push_back(c);
    }
}

void Df(int x)
{
    v[x] = true;
    for (const int& y : G[x])
        if (!v[y])
            Df(y);
    stk.push(x);
}

void DfT(int x)
{
    v[x] = true;
    c.push_back(x);
    for (const int& y : Gt[x])
        if (!v[y])
            DfT(y);
}

void Read()
{
    ifstream fin("ctc.in");
    fin >> n >> m;
    G = Gt = VVI(n + 1);
    v = VB(n + 1);
    int x, y;
    for (int i = 0; i < m; i++)
    {
        fin >> x >> y;
        G[x].push_back(y);
        Gt[y].push_back(x);
    }
    fin.close();
}