Cod sursa(job #3155051)

Utilizator NathanBBerintan Emanuel Natanael NathanB Data 7 octombrie 2023 11:17:31
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.26 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;
const int Nmax = 100001;

int n,m,nrctc;
vl G[Nmax],Gt[Nmax],stk,ctc[Nmax];
bool vis[Nmax];

void dfs(int nod)
{
    vis[nod] = true;
    for(auto c:G[nod])
        if(!vis[c])
        dfs(c);
    stk.eb(nod);
}

void dfst(int nod)
{
    ctc[nrctc].eb(nod);
    vis[nod] = true;
    for(auto c:Gt[nod])
        if(!vis[c])
        dfst(c);
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    cout.tie(nullptr);
    cin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        int x,y;
        cin>>x>>y;
        G[x].eb(y);
        Gt[y].eb(x);
    }
    for(int i=1;i<=n;i++)
        if(!vis[i])
        dfs(i);
    memset(vis,false,sizeof vis);
    for(auto c = stk.rbegin(); c!=stk.rend(); c++)
        if(!vis[*c])
        {
            nrctc++;
            dfst(*c);
        }
    cout<<nrctc<<'\n';
    for(int i=1;i<=nrctc;i++)
    {
        for(auto c:ctc[i])
            cout<<c<<" ";
        cout<<'\n';
    }
    return 0;
}