Cod sursa(job #1375168)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 5 martie 2015 12:27:21
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <iostream>
#include <vector>
#include <bitset>
#include <fstream>

using namespace std;

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

const int maxn = 100005;

int n, m;
vector <int> g[maxn], gt[maxn], tsort, ctc[maxn];
bitset <maxn> used;

inline void dfs(int node) {
    used[node] = 1;
    for(auto it : g[node])
        if(!used[it])
            dfs(it);
    tsort.push_back(node);
}

inline void dfst(int node, int comp) {
    used[node] = 0;
    ctc[comp].push_back(node);
    for(auto it : gt[node])
        if(used[it])
            dfst(it, comp);
}

inline void kosaraju() {
    for(int i = 1 ; i <= n ; ++ i)
        if(!used[i])
            dfs(i);
    int comp = 0;
    for(auto it = tsort.rbegin(); it != tsort.rend() ; ++ it)
        if(used[*it])
            dfst(*it, ++ comp);
    fout << comp << '\n';
    for(int i = 1 ; i <= comp ; ++ i, fout << '\n')
        for(auto it : ctc[i])
            fout << it << ' ';
}

int main() {
    fin >> n >> m;
    for(int i = 1 ; i <= m ; ++ i) {
        int x, y;
        fin >> x >> y;
        g[x].push_back(y);
        gt[y].push_back(x);
    }
    kosaraju();
}