Cod sursa(job #230456)

Utilizator MariusMarius Stroe Marius Data 13 decembrie 2008 23:24:04
Problema Componente tare conexe Scor Ascuns
Compilator cpp Status done
Runda Marime 1.93 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <bitset>
#include <vector>
#include <algorithm>

using namespace std;

const char iname[] = "ctc.in";
const char oname[] = "ctc.out";

#define MAXN  5005
#define FOR(i, a, b)  for (int i = (a); i < (b); ++ i)

vector <int> Go[MAXN], G[MAXN], C[MAXN];

bitset <MAXN> M[MAXN];

void read_in(vector <int>* Go, int& n, const char iname[])
{
    ifstream in(iname);
    int cnt_edges, x, y;

    in >> n;
    for (in >> cnt_edges; cnt_edges > 0; -- cnt_edges) {
        in >> x >> y;
        x --, y --;
        Go[x].push_back(y);
        M[x][y] = 1;
    }
    in.close();
}

void print_out(const vector <int>* G, const int n, const char oname[])
{
    ofstream out(oname);
    vector <int>::const_iterator it;

    out << n << "\n";
    for (int i = 0; i < n; ++ i) {
        for (it = G[i].begin(); it != G[i].end(); ++ it)
            out << *it + 1 << " ";
        out << "\n";
    }
    out.close();
}

int main(void)
{
    int n;
    vector <int>::iterator it;

    read_in(Go, n, iname);

    /* Construieste matricea drumurilor M[][]*/
    FOR (i, 0, n)   M[i][i] = 1;
    FOR (k, 0, n) FOR (i, 0, n) FOR (j, 0, n)
        M[i][j] = M[i][j] | (M[i][k] & M[k][j]);
    /* Construieste graful pentru determinarea componentelor conexe */
    FOR (i, 0, n) FOR (j, 0, n) if (i != j)
        if (M[i][j] & M[j][i])
            G[i].push_back(j), G[j].push_back(i);

    vector <int> used(n, 0);
    queue <int> que;
    int size = 0;
    FOR (i, 0, n) if (used[i] == 0) {
        for (que.push(i), used[i] = 1; !que.empty(); que.pop()) {
            int x = que.front();
            C[size].push_back(x);
            for (it = G[x].begin(); it != G[x].end(); ++ it)
                if (used[*it] == 0)
                    que.push(*it), used[*it] = 1;
        }
        size ++;
    }

    print_out(C, size, oname);

    return 0;
}