Cod sursa(job #3204624)

Utilizator VerestiucAndreiVerestiuc Andrei VerestiucAndrei Data 17 februarie 2024 10:54:59
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <bits/stdc++.h>
#define NMAX 100005
using namespace std;
ifstream fin ("ctc.in");
ofstream fout ("ctc.out");
int n,m;
vector< vector<int> > adj,radj;
bool viz[NMAX];
int comp[NMAX];
vector<int> v,co[NMAX];
void dfs1(int x) {
    viz[x]=1;

    for (auto i : adj[x])
        if (!viz[i]) dfs1(i);

    v.push_back(x);
}
void dfs2(int x,int c) {
    comp[x]=c;
    co[c].push_back(x);

    for (auto i : radj[x])
        if (!comp[i]) dfs2(i,c);
}
int main()
{
    fin>>n>>m;
    adj.resize(n+1); radj.resize(n+1);

    for (int i=0; i<m; i++) {
        int x,y;
        fin>>x>>y;
        adj[x].push_back(y);
        radj[y].push_back(x);
    }

    for (int i=1; i<=n; i++) {
        if (!viz[i]) dfs1(i);
    }

    int cnt=0;
    for (int i=v.size()-1; i>=0; i--){
        if (!comp[v[i]]) dfs2(v[i],++cnt);
    }

    fout<<cnt<<'\n';
    for (int i=1; i<=cnt; i++) {
        for (int j=0; j<co[i].size(); j++)
            fout<<co[i][j]<<' ';
        fout<<'\n';
    }
    return 0;
}