Cod sursa(job #1830358)

Utilizator FlorinHajaFlorin Gabriel Haja FlorinHaja Data 16 decembrie 2016 16:24:14
Problema Componente tare conexe Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

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

stack <int> stiva;
vector<int> ls[100005], lsi[100005], sol[100005];
int viz[100005], n, i, j, x, y, m, ns;

void df(int x) {
    int i;
    viz[x] = 1;
    for (i = 0; i < ls[x].size(); i++) {
        if (viz[ls[x][i]] == 0)
            df(ls[x][i]);
    }
}

void df1(int x) {
    int i;
    viz[x] = n;
    for (i = 0; i < lsi[x].size(); i++) {
        if (viz[lsi[x][i]] == 1)
            df1(lsi[x][i]);
    }
    stiva.push(x);
}

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

    for (i = 1; i <= n; i++)
        if (viz[i] != n) {
            df1(i);
            ns++;
            while (stiva.empty() == 0) {
                sol[ns].push_back(stiva.top());
                stiva.pop();
            }

        }

    g << ns << '\n';
    for (i = 1; i <= ns;i++) {
        for (j = 0; j < sol[i].size(); j++)
            g << sol[i][j] << ' ';
        g << '\n';
    }
    return 0;
}