Cod sursa(job #3373817)

Utilizator Chris_BlackBlaga Cristian Chris_Black Data 7 noiembrie 2026 22:32:40
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.71 kb
#include <bits/stdc++.h>

#define ll long long
#define vi vector<int>
#define vl vector<ll>
#define vvi vector<vi>
#define vvl vector<vl>
#define pii pair<int, int>
#define ff first
#define ss second
#define vpi vector<pii>
#define FOR(i, a, b) for(int i = (a); i <= (b); ++i)
#define FORR(i, a, b) for(int i = (a); i >= (b); --i)
#define pb push_back
using namespace std;
const int N = 1e6 + 9;
const bool testcases = false;

const string INPUT_FILE = "ctc";
ifstream fin(INPUT_FILE + ".in");
ofstream fout(INPUT_FILE + ".out");
#define cin fin
#define cout fout

int n, m;
vvi G(N);
bool instk[N];
vi stk;

int low[N], lvl[N], idx = 0;
vvi ctc;

void Dfs(int x) {
    low[x] = lvl[x] = ++idx;
    stk.pb(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], low[y]);
    }

    if (low[x] == lvl[x]) {
        ctc.pb({});
        int a;
        do {
            a = stk.back();
            stk.pop_back();
            instk[a] = false;

            ctc.back().pb(a);
        } while (a != x);
    }
}

void solve_testcase() {
    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 << ctc.size() << '\n';
    for (auto e : ctc) {
        for (auto f : e) {
            cout << f << ' ';
        }
        cout << '\n';
    }
}

int main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);

    int t = 1;
    if (testcases) cin >> t;
    while (t --) solve_testcase();
    return 0;
}