Cod sursa(job #3350366)

Utilizator Alex283810Mocan Alexandru Vali Alex283810 Data 7 aprilie 2026 13:10:32
Problema Componente tare conexe Scor 10
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");
std::vector<int> graph[100001];
std::stack<int>st;
int lower[100001];
bool comp[100001];
int disc[100001];

std::vector<std::vector<int>> ans;
void tarjan(int curr)
{
    static int time = 0;
    lower[curr] = disc[curr] = ++time;
    comp[time] = true;
    st.push(curr);
    for(int next : graph[curr])
    {
        if(disc[next] == -1)
        {
            tarjan(next);
            lower[curr] = std::min(lower[curr], lower[next]);
        }
        else if(comp[next] == true)
        {
            lower[curr] = std::min(lower[curr], lower[next]);
        }
    }

    if(lower[curr] == disc[curr])
    {
        std::vector<int> v;
        int top;
        do
        {
            top = st.top();
            comp[top] = false;
            st.pop();
            v.push_back(top);
        }while(top != curr);

        ans.push_back(v);
    }
}

int main()
{
    int n, m;
    fin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        int a, b;
        fin >> a >> b;
        graph[a].push_back(b);
    }
    for(int i = 1; i <= n; i++)
    {
        disc[i] = -1;
    }
    for(int i = 1; i <= n; i++)
    {
        if(disc[i] == -1)
        {
            tarjan(i);
        }
    }
    fout << ans.size() << '\n';
    for(int i = 0; i < ans.size(); i++, fout << '\n')
        for(int j = 0; j < ans[i].size(); j++)
            fout << ans[i][j] << ' ';
    return 0;
}