Cod sursa(job #2427535)

Utilizator PrekzursilAndrei Visalon Prekzursil Data 31 mai 2019 23:14:34
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <bits/stdc++.h>
#define DMAX 100009
using namespace std;
vector <int> g[DMAX], gt[DMAX], c[DMAX];
int use[DMAX], a, b, n, m, nrc;
stack <int> s;
void dfs1(int k) {
    use[k]=1;
    for(auto i : g[k])
        if(!use[i])
            dfs1(i);
    s.push(k);
}
void dfs2(int k) {
    use[k]=1;
    for(auto i : gt[k])
        if(!use[i])
            dfs2(i);
    c[nrc].push_back(k);
}
int main()
{
    freopen("ctc.in", "r", stdin);
    freopen("ctc.out", "w", stdout);
    cin>>n>>m;
    for(int i=1;i<=m;i++)
    {
        scanf("%i %i", &a, &b);
        g[a].push_back(b);
        gt[b].push_back(a);
    }
    for(int i=1;i<=n;i++)
        if(!use[i])
            dfs1(i);
    memset(use, 0, sizeof use);
    while(!s.empty()) {
        int a=s.top();
        s.pop();
        if(!use[a])
            nrc++,
            dfs2(a);
    }
    cout<<nrc<<'\n';
    for(int i = 1; i <= nrc; i++) {
        for(auto j : c[i])
           printf("%i ", j);
        printf("\n");
    }
    return 0;
}