Cod sursa(job #1363159)

Utilizator tudorv96Tudor Varan tudorv96 Data 26 februarie 2015 19:21:40
Problema Componente tare conexe Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.22 kb
#include <fstream>
#include <vector>
using namespace std;

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

const int N = 1e+005 + 5;

vector <int> g[N], gt[N], nodes, comp[N];
vector <bool> viz(N, 0);

int n, m, c;


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

void dfst(int x) {
    viz[x] = 0;
    comp[c].push_back(x);
    for (vector <int> :: iterator it = gt[x].begin(); it != gt[x].end(); ++it)
        if (viz[*it])
            dfst(*it);

}

int main() {
    fin >> n >> m;
    for (int x, y, i = 1; i <= m; ++i) {
        fin >> x >> y;
        g[x].push_back(y);
        gt[y].push_back(x);
    }
    for (int i = 1; i <= n; ++i)
        if (!viz[i])
            dfs(i);
    for (vector <int> :: reverse_iterator it = nodes.rbegin(); it != nodes.rend(); ++it)
        if (viz[*it]) {
            dfst(*it);
            c++;
        }
    fout << c << "\n";
    for (int i = 0; i < c; ++i) {
        for (vector <int> :: iterator it = comp[i].begin(); it != comp[i].end(); ++it)
            fout << *it << " ";
        fout << "\n";
    }
}