Cod sursa(job #3155860)

Utilizator NathanBBerintan Emanuel Natanael NathanB Data 9 octombrie 2023 23:15:53
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.56 kb
#include <bits/stdc++.h>

using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");
#define cin fin
#define cout fout
#define pb push_back
#define eb emplace_back
#define Inf 0x3f3f3f3f
typedef long long ll;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<pair<ll,ll>> vpl;
const int Nmax = 100001;

int n,m,lvl[Nmax],low[Nmax],id,cnt,comp[Nmax];
vvl G;
bool instack[Nmax];
stack<int> stk;
void Dfs(int nod)
{
    stk.push(nod);
    instack[nod] = true;
    lvl[nod] = low[nod] = ++id;
    for(auto c:G[nod])
    if(!lvl[c])
    {
        Dfs(c);
        low[nod] = min(low[nod],low[c]);
    }
    else if(instack[c]==true)
        low[nod] = min(low[nod],lvl[c]);
    if(low[nod]==lvl[nod])
    {
        cnt++;
        while(true)
        {
            int a = stk.top();
            stk.pop();
            comp[a] = cnt;
            instack[a] = false;
            if(a==nod)
                break;
        }
    }
}

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

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cin>>n>>m;
    G = vvl(Nmax);
    for(int i=1;i<=m;i++)
    {
        int x,y;
        cin>>x>>y;
        G[x].eb(y);
        //G[y].eb(x);
    }
    Tarjan();
    vvl CTC(cnt+1);
    for(int i=1;i<=n;i++)
        CTC[comp[i]].eb(i);
    cout<<cnt<<'\n';
    for(int i=1;i<=cnt;i++)
    {
        for(auto c:CTC[i])
            cout<<c<<" ";
        cout<<'\n';
    }
    return 0;
}