Cod sursa(job #3285848)

Utilizator Chris_BlackBlaga Cristian Chris_Black Data 13 martie 2025 15:13:12
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <bits/stdc++.h>
#define vi vector<int>
#define vvi vector<vi>
#define pb push_back
#define pii pair<int, int>
#define ff first
#define ss second
#define FOR(i, a, b) for(int i = a; i <= b; ++i)
#define FORR(i, a, b) for(int i = a; i >= b; --i)

using namespace std;
const string TASK("ctc");
ifstream fin(TASK + ".in");
ofstream fout(TASK + ".out");
#define cin fin
#define cout fout

const int N = 1e6 + 9;
const bool test_case = false;

int n, m;
vvi G(N);

stack<int> stk;
bool instk[N];
int lvl[N], low[N], idx;
vvi c;
void Dfs(int x)
{
    lvl[x] = low[x] = ++idx;
    stk.push(x);
    instk[x] = true;

    for(auto y : G[x])
        if(!lvl[y])
    {
        Dfs(y);
        low[x] = min(low[x], low[y]);
    }
    else if(instk[y])low[x] = min(low[x], lvl[y]);

    if(lvl[x] == low[x])
    {
        c.pb({});
        while(true)
        {
            int a = stk.top();
            stk.pop();
            instk[a] = false;
            c.back().pb(a);
            if(a == x)break;
        }
    }
}

void solve()
{
    cin >> n >> m;

    int x, y;
    FOR(i, 1, m)
    {
        cin >> x >> y;
        G[x].pb(y);
    }

    FOR(i, 1, n)
        if(!lvl[i])
            Dfs(i);

    cout << c.size() << '\n';
    for(auto e : c)
    {
        for(auto i : e)cout << i << ' ';
        cout << '\n';
    }
}

int main()
{
    int t = 1;
    if(test_case)cin >> t;
    while(t --)
        solve();
    return 0;
}