Cod sursa(job #846107)

Utilizator deneoAdrian Craciun deneo Data 1 ianuarie 2013 15:24:09
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include <fstream>
#include <vector>
#include <algorithm>
#include <stack>
#include <iostream>
using namespace std;

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

#define MAXN 110000

vector <int> G[MAXN];
vector <int> con, id(MAXN), how_high(MAXN);
vector < vector <int> > rez;
stack <int> S;

int N, M, indic, in_stack[MAXN];

void read() {
    fin >> N >> M;
    for (int i = 1; i <= M; ++i) {
        int x, y;
        fin >> x >> y;
        G[x].push_back(y);
    }
}

void tarjan(int nod) {
    id[nod] = how_high[nod] = ++indic;
    in_stack[nod] = 1; S.push(nod);

    for (int i = 0; i < G[nod].size(); ++i) {
        if (id[G[nod][i]] == -1) {
            tarjan (G[nod][i]);
            how_high[nod] = min (how_high[nod], how_high[G[nod][i]]);
        }
        else if (in_stack[G[nod][i]])
            how_high[nod] = min (how_high[nod], how_high[G[nod][i]]);
    }

    if (id[nod] == how_high[nod]) {
        int node;
        con.clear();
        do {
            node = S.top();
            S.pop();
            con.push_back(node);
            in_stack[node] = 0;
        } while (node != nod);

        rez.push_back(con);
    }
}


void solve() {
    id.assign(N + 1, -1);

    for (int i = 1; i <= N; ++i)
        if (id[i] == -1)
            tarjan(i);
}

void print() {
    fout << rez.size() << "\n";

    for (int i = 0; i < rez.size(); ++i) {
        for (int j = 0; j < rez[i].size(); ++j)
            fout << rez[i][j] << " ";
        fout << "\n";
    }
}

int main() {
    read();
    solve();
    print();
    return 0;
}