Cod sursa(job #1891053)

Utilizator wilson182Alexandrina Panfil wilson182 Data 23 februarie 2017 18:29:16
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <fstream>
#include <vector>
#define N 100005
using namespace std;
 
ifstream f("ctc.in");
ofstream g("ctc.out");
 
vector <int> ls[N], ls_inv[N], sl;
int n, m, i, j, x, y;
int viz[N];
int care[N], 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;
}