Cod sursa(job #1888909)

Utilizator FlorinHajaFlorin Gabriel Haja FlorinHaja Data 22 februarie 2017 13:43:32
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <fstream>
#include <vector>

using namespace std;

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

vector <int> ls[100005], ls_inv[100005], sl;
int n, m, i, j, x, y;
int viz[100005];
int care[100005], nc;
vector<vector<int> > sol;

void df1(int x) {
    int i, y, l;
    l = ls[x].size();
    viz[x] = 1;
    for (i = 0; i< l; i++) {
        y = ls[x][i];
        if (viz[y] == 0)
            df1(y);
    }
    care[++nc] = x;
}

void df2(int x) {
    int i, y, l;
    l = ls_inv[x].size();

    viz[x] = 2;
    for (i = 0; i < l; i++) {
        y = ls_inv[x][i];
        if (viz[y] == 1)
            df2(y);
    }
    sl.push_back(x);
}

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) {
            df1(i);
        }
    for (i = nc; i >= 1; i--)
        if (viz[care[i]] == 1) {
            sl.clear();
            df2(care[i]);
            sol.push_back(sl);
        }
    g << (y = sol.size()) <<'\n';
    for (i = 0; i < y; i++) {
        x = sol[i].size();
        for (j = 0; j < x; j++) {
            g << sol[i][j] << ' ';
        }
        g << '\n';
    }
    return 0;
}