Cod sursa(job #1966191)

Utilizator FlorinHajaFlorin Gabriel Haja FlorinHaja Data 14 aprilie 2017 23:13:11
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.08 kb
#include <fstream>
#include <vector>

using namespace std;

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

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

void dfs1(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] == 0) dfs1(y);
    }
    stv[++vf] = x;
}

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

int main() {
    f >> n >> m;
    for (i = 1; i <= m; i++) {
        f >> x >> y;
        ls[x].push_back(y);
        lr[y].push_back(x);
    }
    for (i = 1; i <= n; i++)
        if (viz[i] == 0) dfs1(i);
    for (i = n; i >= 1; i--)
        if (viz[stv[i]] == 1){K++;dfs2(stv[i]);}
    g << K << '\n';
    for (i = 1; i <= K; i++) {
        for (j = 0; j < sol[i].size(); j++)
            g << sol[i][j] << ' ';
        g << '\n';
    }
}