Cod sursa(job #1365824)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 28 februarie 2015 15:56:01
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>

using namespace std;

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

const int maxn = 100005;

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

inline void dfst(int node, int comp) {
    used[node] = 0;
    ctc[comp].push_back(node);
    for(vector <int> :: iterator it = gt[node].begin() ; it != gt[node].end() ; ++ it)
        if(used[*it])
            dfst(*it, comp);
}

inline void dfs(int node) {
    used[node] = 1;
    for(vector <int> :: iterator it = g[node].begin() ; it != g[node].end() ; ++ it)
        if(!used[*it])
            dfs(*it);
    tsort.push_back(node);
}

int main() {
    fin >> n >> m;
    for(int i = 0 ; i < m ; ++ i) {
        int x, y;
        fin >> x >> y;
        g[x].push_back(y);
        gt[y].push_back(x);
    }
    for(int i = 1 ; i <= n ; ++ i)
        if(!used[i])
            dfs(i);
    int comp = 0;
    for(vector <int> :: reverse_iterator 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(vector <int> :: iterator it = ctc[i].begin() ; it != ctc[i].end() ; ++ it)
            fout << *it << ' ';
}