Cod sursa(job #1402110)

Utilizator AnduuFMI Alexandru Banu Anduu Data 26 martie 2015 12:35:12
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.68 kb
#include <fstream>
#include <vector>
#include <stack>
#include <cstring>

#define NMAX 100001
using namespace std;

vector<int> v[NMAX], vt[NMAX], sol[NMAX];
stack<int> s;
int n, m, comp;
bool viz[NMAX];

void read() {
    int i, x, y;

    ifstream in ("ctc.in");
    in >> n >> m;
    for (i = 1; i <= m; i++) {
        in >> x >> y;
        v[x].push_back(y);
    }
    in.close();
}

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

void dft(int x) {
    viz[x] = 1;
    for (vector<int>::iterator it = vt[x].begin(); it != vt[x].end(); it++)
        if (!viz[*it])
            dft(*it);
    sol[comp].push_back(x);
}

int vizitat(int nod) {
    int i;

    for (i = nod; i <= n; i++)
        if (!viz[i])
            return i;
    return 0;
}

void invert() {
    int i;

    for (i = 1; i <= n; i++)
        for (vector<int>::iterator it = v[i].begin(); it != v[i].end(); it++)
            vt[*it].push_back(i);
}

void write() {
    ofstream out("ctc.out");
    out << comp << '\n';
    for (int i = 1; i <= comp; i++) {
        for (vector<int>::iterator it = sol[i].begin(); it != sol[i].end(); it++)
            out << *it << ' ';
        out << '\n';
    }
    out.close();
}

int main() {
    int nod;

    read();

    nod = 1;
    while (nod = vizitat(nod))
        df(nod);
    memset(viz, 0, sizeof(viz));
    invert();
    while (!s.empty()) {
        nod = s.top();
        s.pop();
        if (!viz[nod]) {
            comp++;
            dft(nod);
        }
    }

    write();
    return 0;
}