Cod sursa(job #3318848)

Utilizator PaulTPaul Tirlisan PaulT Data 29 octombrie 2025 13:20:26
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.57 kb
#include <fstream>
#include <vector>
#include <stack>
using namespace std;

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

int n;
VVI G, ctc;
VI index, lowlink;
stack<int> stk;
VB inStack;

void Read();
void Tarjan(int x, int& level);
void Write();

int main()
{
    int level = 1;
    Read();
    for (int x = 1; x <= n; ++x)
        if (!index[x])
            Tarjan(x, level);
    Write();
}

void Read()
{
    int m;
    ifstream fin("ctc.in");
    fin >> n >> m;
    G = VVI(n + 1);
    index = lowlink = VI(n + 1);
    inStack = VB(n + 1);
    
    int x, y;
    while (m--)
    {
        fin >> x >> y;
        G[x].push_back(y);
    }
    
    fin.close();
}

void Tarjan(int x, int& level)
{
    index[x] = lowlink[x] = level;
    level++;
    stk.push(x);
    inStack[x] = true;
    
    for (const int y: G[x])
    {
        if (!index[y])
        {
            Tarjan(y, level);
            lowlink[x] = min(lowlink[x], lowlink[y]);
        }
        else if (inStack[y])
            lowlink[x] = min(lowlink[x], index[y]);
    }
    
    if (lowlink[x] == index[x])
    {
        VI c;
        int y;
        while (!stk.empty())
        {
            y = stk.top();
            stk.pop();
            inStack[y] = false;
            c.push_back(y);
            if (y == x)
                break;
        }
        
        ctc.push_back(move(c));
    }
}

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