Cod sursa(job #2095065)

Utilizator ancabdBadiu Anca ancabd Data 26 decembrie 2017 21:13:49
Problema Componente tare conexe Scor 100
Compilator cpp 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>;

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

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

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

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 Kosaraju()
{
    for (int x = 1; x <= n; x++)
        if (!v[x])
            Df(x);
    int x;
    v = VB(n + 1);
    while (!stk.empty())
    {
        x = stk.top();
        stk.pop();
        if (v[x])
            continue;
        c.clear();
        DfT(x);
        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 = Gt = VVI(n + 1);
    v = VB(n + 1);
    int x, y;
    while (m--)
    {
        fin >> x >> y;
        G[x].push_back(y);
        Gt[y].push_back(x);
    }
    fin.close();
}