Cod sursa(job #2799512)

Utilizator gasparrobert95Gaspar Robert Andrei gasparrobert95 Data 13 noiembrie 2021 12:02:46
Problema Componente tare conexe Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("ctc.in");
ofstream fout("ctc.out");
int n, m, sol;
bool viz[100005], viz2[100005];
vector <int> g[100005], g2[100005], rez[100005];
stack <int> s;

void dfs(int nod) {
    viz[nod] = true;
    for (int i = 0; i < g[nod].size(); ++i) {
        int next = g[nod][i];
        if (!viz[next])
            dfs(next);
    }
    s.push(nod);
    return;
}

void dfs2(int nod) {
    viz2[nod] = true;
    rez[sol].push_back(nod);
    for (int i = 0; i < g2[nod].size(); ++i) {
        int next = g2[nod][i];
        if (!viz2[next])
            dfs2(next);
    }
    return;
}

int main() {
    fin >> n >> m;
    while (m--) {
        int a, b;
        fin >> a >> b;
        g[a].push_back(b);
        g2[b].push_back(a);
    }
    for (int i = 1; i <= n; ++i)
        if (!viz[i])
            dfs(i);
    while (!s.empty()) {
        int nod = s.top();
        s.pop();
        if (!viz2[nod]) {
            ++sol;
            dfs2(nod);
        }
    }
    fout << sol << "\n";
    for (int i = 1; i <= sol; ++i) {
        for (int j = 0; j < rez[i].size(); ++j)
            fout << rez[i][j] << " ";
        fout << "\n";
    }
    return 0;
}