Cod sursa(job #2147675)

Utilizator FlorinHajaFlorin Gabriel Haja FlorinHaja Data 28 februarie 2018 21:42:00
Problema Componente tare conexe Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <fstream>
#include <vector>

using namespace std;

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

const int nmax = 100005;
int n, m, i, j, x, y, stiva[nmax], vf, K, viz[nmax];
vector<int> ls[nmax], ls_inv[nmax], sol[nmax];

void dfs(int x) {
    int l = ls[x].size(), i, y;
    viz[x] = 1;
    for (i = 0; i < l; i++) {
        y = ls[x][i];
        if (viz[y]) continue;
        dfs(y);
    }
    stiva[++vf] = x;
}

void dfs_inv(int x) {
    int l = ls_inv[x].size(), i, y;
    viz[x] = 0;
    sol[K].push_back(x);
    for (i = 0; i < l; i++) {
        y = ls_inv[x][i];
        if (viz[y] == 0) continue;
        dfs_inv(y);
    }
}

int main() {
    f >> n >> m;
    while (m--) {
        f >> x >> y;
        ls[x].push_back(y);
        ls_inv[y].push_back(x);
    }
    for (i = 1; i <= n; i++)
        if (viz[i] == 0)
            dfs(i);

    for (i = n; i >= 1; i--)
        if (viz[stiva[i]] == 1) {
            K++;
            dfs_inv(stiva[i]);
        }
    g << K << '\n';
    for (i = 1; i <= K; i++) {
        for (vector<int>::iterator w = sol[i].begin(); w != sol[i].end(); w++)
            g << *w << ' ';
        g << '\n';
    }

    return 0;
}