Cod sursa(job #2033360)

Utilizator ioanailincaMoldovan Ioana Ilinca ioanailinca Data 6 octombrie 2017 18:00:33
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.53 kb
/// algoritmul lui Kosaraju

#include <fstream>
#include <vector>
#include <stack>
#include <algorithm>

using namespace std;

ifstream fin("ctc.in");
ofstream fout("ctc.out");

const int NMAX = 100001;

int n, m, componente;
vector <vector <int>> v, vt;
bool viz[NMAX];
stack <int> stk;
vector <vector <int>> ans;

inline void readData() {
    fin >> n >> m;
    v = vt = vector <vector <int>> (n + 1);
    int x, y;

    while (m--) {
        fin >> x >> y;
        v[x].push_back(y);
        vt[y].push_back(x);
    }
}

void dfs(int node) {
    viz[node] = 1;
    for (int t: v[node]) {
        if (viz[t])
            continue;
        dfs(t);
    }
    stk.push(node);
}

void dfst(int node) {
    viz[node] = 0;
    for (int t: vt[node]) {
        if (!viz[t])
            continue;
        dfst(t);
    }
    ans[componente - 1].push_back(node);
}

inline void process() {
    for (int i = 1; i <= n; ++i)
        if (!viz[i])
            dfs(i);

    int x;
    while (stk.size()) {
        x = stk.top();
        stk.pop();
        if (viz[x]) {
            componente++;
            ans.push_back(vector <int>());
            dfst(x);
            sort(ans[componente - 1].begin(), ans[componente - 1].end());
        }
    }

    fout << componente << '\n';
    for (auto vec: ans) {
        for (int t: vec)
            fout << t << ' ';
        fout << '\n';
    }
}

int main()
{
    readData();
    process();

    fin.close();
    fout.close();
    return 0;
}