Cod sursa(job #3199959)

Utilizator Chris_BlackBlaga Cristian Chris_Black Data 3 februarie 2024 08:35:21
Problema Componente tare conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.49 kb
#include <bits/stdc++.h>
#define PI pair<int, int>
#define F first
#define S second
#define VI vector<int>
#define ff first
#define ss second
#define pb push_back
#define ull unsigned long long
#define ll long long
#define vi vector<int>
#define vvi vector<vi>
#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 = 1e5 + 9;

int n, m;
vvi G(N);

int low[N], lvl[N];
bool instk[N];
stack<int> stk;
int idx;

vi c;
vvi ctc;

void Dfs(int x)
{
    low[x] = lvl[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(low[x] == lvl[x])
    {
        c.clear();
        while(true)
        {
            int a = stk.top();
            instk[a] = false;
            stk.pop();

            c.pb(a);

            if(a == x)break;
        }
        ctc.pb(c);
    }
}

int main()
{
    cin >> n >> m;

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

    Dfs(1);

    cout << ctc.size() << '\n';
    for(auto i : ctc)
    {
        for(auto j : i)
            cout << j << ' ';
        cout << '\n';
    }
    return 0;
}