Cod sursa(job #1368727)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 2 martie 2015 19:39:22
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>

using namespace std;

const int maxn = 100005;

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

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

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);
    discovered.push_back(node);
}

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);
}

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);
    }
    for(int i = 1 ; i <= n ; ++ i)
        if(!used[i])
            dfs(i);
    int ctcsz = 0;
    for(vector <int> :: reverse_iterator it = discovered.rbegin() ; it != discovered.rend() ; ++ it)
        if(used[*it])
            dfst(*it, ++ ctcsz);
    fout << ctcsz << '\n';
    for(int i = 1 ; i <= ctcsz ; ++ i, fout << '\n')
        for(vector <int> :: iterator it = ctc[i].begin() ; it != ctc[i].end() ; ++ it)
            fout << *it << ' ';
}