Cod sursa(job #3216023)

Utilizator Chris_BlackBlaga Cristian Chris_Black Data 15 martie 2024 16:09:52
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.44 kb
#include <bits/stdc++.h>
#define pii pair<int, int>
#define ff first
#define ss second
#define vi vector<int>
#define vvi vector<vi>
#define pb push_back
#define eb emplace_back


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], idx;
stack<int> stk;
bool instk[N];
vvi ctc;
vi c;

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

            c.pb(a);

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


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

    cin >> n >> m;

    int x, y;
    for(int i = 1; i <= m; ++i)
    {
        cin >> x >> y;
        G[x].pb(y);
    }

    for(int i = 1; i <= n; ++i)
        if(!lvl[i])
            Dfs(i);

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