Cod sursa(job #2759950)

Utilizator bigmixerVictor Purice bigmixer Data 21 iunie 2021 15:59:13
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.65 kb
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define ld long double
#define all(a) (a).begin(), (a).end()
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#define fr first
#define sc second
#define int long long
#define rc(s) return cout<<s,0
#define rcc(s) cout<<s,exit(0)

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

const int nmax = 100005;

int n, m;
vector<int>nod[nmax], nod2[nmax];
bitset<nmax>viz;
vector<int>aux, st;
vector<vector<int>>componente;

void dfs(int s){
    viz[s] = 1;
    for(auto it : nod[s]){
        if(!viz[it]) dfs(it);
    }
    st.push_back(s);
}


void dfs2(int s){
    viz[s] = 1;
    aux.push_back(s);
    for(auto it : nod2[s]){
        if(!viz[it]) dfs2(it);
    }
}

int32_t main(){
    ios_base::sync_with_stdio(false);cin.tie(0);cerr.tie(0);cout.tie(0);
    freopen("ctc.in", "r", stdin);
    freopen("ctc.out", "w", stdout);
    cin >> n >> m;
    for(int i=1;i<=m;i++){
        int x, y;
        cin >> x >> y;
        nod[x].push_back(y);
        nod2[y].push_back(x);
    }
    for(int i=1;i<=n;i++){
        if(!viz[i]){
            dfs(i);
        }
    }
    reverse(all(st));
    viz.reset();
    for(auto it : st){
        if(!viz[it]){
            aux.clear();
            dfs2(it);
            componente.push_back(aux);
        }
    }
    cout << (int)componente.size() << '\n';
    for(auto it : componente){
        for(auto it1 : it){
            cout << it1 << ' ';
        }
        cout << '\n';
    }
}

// 1. Solve the problem
// 2. ???
// 3. Profit

// https://www.youtube.com/watch?v=5qap5aO4i9A