Cod sursa(job #2792070)

Utilizator PaulTPaul Tirlisan PaulT Data 31 octombrie 2021 20:05:24
Problema Componente tare conexe Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <fstream>
#include <vector>
#include <stack>
#include <cmath>
using namespace std;

int n, m, level;
vector<vector<int>> G;
stack<int> stk;
vector<int> L, niv, cc, color;
vector<vector<int>> ctc;

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

int main()
{
    Read();
    for (int x = 1; x <= n; x++)
        if (!color[x])
            Dfs(x);
    
    Write();
}

void Dfs(int x)
{
    color[x] = 1;
    niv[x] = L[x] = ++level;
    stk.push(x);
    for (const int& y : G[x])
    {
        switch (color[y])
        {
            case 0: Dfs(y); L[x] = min(L[x], L[y]); break;
            case 1: L[x] = min(L[x], niv[y]); break;
            default: break;
        }
    }
    
    int y;
    if (L[x] == niv[x])
    {
        cc = vector<int>();
        while (!stk.empty())
        {
            y = stk.top();
            stk.pop();
            cc.emplace_back(y);
            if (y == x)
                break;
        }
        ctc.emplace_back(cc);
    }
}

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

void Read()
{
    ifstream fin("ctc.in");
    fin >> n >> m;
    G = vector<vector<int>>(n + 1);
    color = L = niv = vector<int>(n + 1);
    
    int x, y;
    while (m--)
    {
        fin >> x >> y;
        G[x].emplace_back(y);
    }
}