Cod sursa(job #2668633)

Utilizator gunther41Ionut Buzamat Alexandru gunther41 Data 5 noiembrie 2020 06:01:54
Problema Componente tare conexe Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.97 kb
#include <bits/stdc++.h>
using namespace std;

ifstream f("ctc.in");
ofstream o("ctc.out");

int n, m, nr, sz=100009;
bool v[sz];
vector<int> a[sz], b[sz], noduri, ctc[sz];


void dfs1(int x) {
    v[x] = 1;
    for(auto next: a[x])
        if(!v[next])
            dfs1(next);
    noduri.push_back(x);
}

void dfs2(int x) {
    v[x] = 1;
    ctc[nr].push_back(x);
    for(auto next: b[x])
        if(!v[next])
            dfs2(next);
}



int main() {
    f >> n >> m;
    while(m--) {
        int x, y;
        f >> x >> y;
        a[x].push_back(y);
        b[y].push_back(x);
    }

    for(int i = 1; i <= n; i++)
        if(!v[i])
            dfs1(i);
    for(int i = 1; i <= n; i++)
        v[i] = 0;
    for(int i = noduri.size()-1; i >= 0; i--)
        if(!v[noduri[i]]) {
            nr++;
            dfs2(noduri[i]);
        }

    o<<nr<<'\n';
    for(int i = 1; i <= nr; i++){
    for(auto x: ctc[i])o<<x<<' '; o << '\n';}
}