Cod sursa(job #3301643)

Utilizator jumaracosminJumara Cosmin-Mihai jumaracosmin Data 28 iunie 2025 19:56:50
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <bits/stdc++.h>

std::ifstream fin("ctc.in");
std::ofstream fout("ctc.out");

//#define fin std::cin 
//#define fout std::cout 

const int nmax = 1e5 + 5;

int n, m;
std::vector<int> graph[nmax];
int curr_idx;
int lowlink[nmax], idx[nmax];
bool on_stack[nmax];
std::stack<int> st;

int ctc_count;
std::vector<int> ctc_comp[nmax];

void buildCTC(int node)
{
    idx[node] = ++curr_idx;
    lowlink[node] = idx[node];
    on_stack[node] = true;
    st.push(node);

    for(auto adj : graph[node])
    {
        if(!idx[adj])
        {
            buildCTC(adj);
            lowlink[node] = std::min(lowlink[node], lowlink[adj]);
        }
        else if(on_stack[adj])
            lowlink[node] = std::min(lowlink[node], lowlink[adj]);
    }


    if(lowlink[node] == idx[node])
    {
        ctc_count++;

        int curr_node;

        do
        {
            curr_node = st.top();
            st.pop();
            on_stack[curr_node] = false;
            ctc_comp[ctc_count].push_back(curr_node);
        }
        while(curr_node != node);
    }
}

int main() 
{
    fin >> n >> m;
    for(int i = 1; i <= m; ++i)
    {
        int x, y;
        fin >> x >> y;
        graph[x].push_back(y);
    }

    for(int i = 1; i <= n; ++i)
        if(!idx[i])
            buildCTC(i);

    fout << ctc_count << "\n";
    for(int i = 1; i <= ctc_count; ++i, fout << "\n")
        for(auto node : ctc_comp[i])
            fout << node << " ";

    return 0;
}