Cod sursa(job #1382431)

Utilizator mariusadamMarius Adam mariusadam Data 8 martie 2015 23:57:13
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.3 kb
#include <fstream>
#include <vector>
#include <stack>
#define n_max 100002

using namespace std;

ifstream r("ctc.in");
ofstream w("ctc.out");

vector <int> g[n_max], gt[n_max], ctc[n_max];
stack <int> topo;
int viz[n_max], n, m, nrc;

void df(int nod) {
    viz[nod]=1;
    for(vector <int>::iterator it=g[nod].begin(); it!=g[nod].end(); it++)
        if (viz[*it]==0)
            df(*it);
    topo.push(nod);
}

void dft(int nod) {
    viz[nod]=1;
    for (vector <int>::iterator it=gt[nod].begin(); it!=gt[nod].end(); it++)
        if (viz[*it]==0)
            dft(*it);
    ctc[nrc].push_back(nod);
}

void read() {
    int i,j,k;
    r>>n>>m;
    for (k=0; k<m; k++) {
        r>>i>>j;
        g[i].push_back(j);
        gt[j].push_back(i);
    }
}

int main() {
    read();
    for (int i=1; i<=n; i++)
        if (viz[i]==0)
            df(i);
    for (int i=1; i<=n; i++)
        viz[i]=0;
    while (!topo.empty()) {
        if (viz[topo.top()]==0) {
            nrc++;
            dft(topo.top());
        }
        topo.pop();
    }
    w<<nrc<<"\n";
    for (int i=1; i<=nrc; i++) {
        for (vector <int>::iterator it=ctc[i].begin(); it!=ctc[i].end(); it++)
            w<<*it<<" ";
        w<<"\n";
    }
    r.close();
    w.close();
    return 0;
}