Cod sursa(job #1488938)

Utilizator eu3neuomManghiuc Teodor-Florin eu3neuom Data 20 septembrie 2015 11:06:03
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.72 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <stack>

using namespace std;

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

const int NMax = 1e5 + 5;

vector < int > Go[NMax], Gi[NMax], G[NMax], where;
stack < int > discovered;
bitset < NMax > used;

inline void Read(int &n){
    int m, x, y;
    fin >> n >> m;
    while(m--){
        fin >> x >> y;
        Go[x].push_back(y);
        Gi[y].push_back(x);
    }
}

void DFP(vector < int > *G, const int now){
    vector < int > ::iterator it;
    used[now] = 1;
    for(it = G[now].begin(); it != G[now].end(); it++){
        if(!used[*it]){
            DFP(G, *it);
        }
    }
    discovered.push(now);
}

void DFM(vector < int > *G, const int now, const int cont){
    vector < int > ::iterator it;
    where[now] = cont;
    for(it = G[now].begin(); it != G[now].end(); it++){
        if(where[*it] == 0){
            DFM(G, *it, cont);
        }
    }
}

inline void Print(const int cont){
    vector < int > ::iterator it;
    fout << cont - 1 << "\n";
    for(int i = 1; i < cont; i++){
        for(it = G[i].begin(); it != G[i].end(); it++){
            fout << *it << " ";
        }
        fout << "\n";
    }
}

int main(){
    int n, cont;
    Read(n);
    for(int i = 1; i <= n; i++){
        if(!used[i]){
            DFP(Go, i);
        }
    }
    where.resize(n + 1);
    cont = 1;
    while(!discovered.empty()){
        if(where[discovered.top()] == 0){
            DFM(Gi, discovered.top(), cont);
            cont++;
        }
        discovered.pop();
    }
    for(int i = 1; i <= n; i++){
        G[where[i]].push_back(i);
    }
    Print(cont);
    return 0;
}