Cod sursa(job #2868831)

Utilizator 100pCiornei Stefan 100p Data 11 martie 2022 10:53:13
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <bits/stdc++.h>
#define fastio ios_base::sync_with_stdio(NULL),cin.tie(NULL),cout.tie(NULL);
#define pb push_back
#define mp make_pair
#define ll long long
#define ull unsigned long long
#define MAX 100000
#define FILES freopen("ctc.in","r",stdin);\
              freopen("ctc.out","w",stdout);
#define mod 666013
#define int ll
using namespace std;
int n,m,a,b,nrc;
vector<int> v[MAX+5],v2[MAX+5],comp[MAX+5];
bool check[MAX+5],check2[MAX+5];
stack<int>s;
void dfs(int x)
{
    check[x] = 1;
    for(auto i : v[x])
        if(!check[i]) dfs(i);
    s.push(x);
}
void dfs2(int x)
{
    comp[nrc].pb(x);
    check2[x] = 1;
    for(auto i : v2[x])
        if(!check2[i]) dfs2(i);
}
signed main()
{
    fastio
    FILES
    cin >> n >> m;
    for(int i = 1;i <= m; ++i)
    {
        cin >> a >> b;
        v[a].pb(b),v2[b].pb(a);
    }
    for(int i = 1;i <= n; ++i)
        if(!check[i]) dfs(i);
    while(!s.empty())
    {
        int x = s.top();
        if(!check2[x])
        {
            nrc++;
            dfs2(x);
        }
        s.pop();
    }
    cout << nrc << '\n';
    for(int i = 1;i <= nrc; ++i,cout << '\n')
        for(auto j : comp[i]) cout << j << ' ';
}