Cod sursa(job #3288072)

Utilizator Chris_BlackBlaga Cristian Chris_Black Data 20 martie 2025 14:17:05
Problema Componente tare conexe Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.11 kb
#include <bits/stdc++.h>
#include <bits/extc++.h>
using namespace std;
using namespace __gnu_pbds;


#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)
#define ll long long
#define int long long

struct custom_hash_pair {
	static uint64_t splitmix64(uint64_t x) {
		x += 0x9e3779b97f4a7c15;
		x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9;
		x = (x ^ (x >> 27)) * 0x94d049bb133111eb;
		return x ^ (x >> 31);
	}

	size_t operator()(pair<uint64_t,uint64_t> x) const {
		static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count();
		return splitmix64(x.first + FIXED_RANDOM)^(splitmix64(x.second + FIXED_RANDOM) >> 1);
	}
};

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


const int N = 1e6 + 9, Inf = 0x3f3f3f3f;
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({});
        int a;
        do
        {
            a = stk.top();
            stk.pop();
            c.back().pb(a);
        }while(a != x);
    }
}

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';
    }
}

signed main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    int t = 1;
    if (test_case) cin >> t;
    while (t--)
        solve();
    return 0;
}