Cod sursa(job #2792071)

Utilizator PaulTPaul Tirlisan PaulT Data 31 octombrie 2021 20:13:05
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 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;
vector<bool> inStack, visited;
vector<vector<int>> ctc;

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

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

void Dfs(int x)
{
    visited[x] = true;
    niv[x] = L[x] = ++level;
    stk.push(x);
    inStack[x] = true;
    for (const int& y : G[x])
    {
        if (!visited[y])
        {
            Dfs(y);
            L[x] = min(L[x], L[y]);
        }
        else
            if (inStack[y])
                L[x] = min(L[x], niv[y]);
    }
    
    int y;
    if (L[x] == niv[x])
    {
        cc = vector<int>();
        while (!stk.empty())
        {
            y = stk.top();
            stk.pop();
            inStack[y] = false;
            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);
    L = niv = vector<int>(n + 1);
    visited = inStack = vector<bool>(n + 1);
    
    int x, y;
    while (m--)
    {
        fin >> x >> y;
        G[x].emplace_back(y);
    }
}