Cod sursa(job #1090270)

Utilizator pgeorgeGeorge Pirlea pgeorge Data 22 ianuarie 2014 15:31:27
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.06 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>
#include <cstring>


#define MAX_N (100000)
#define NEVIZITAT (0)
#define IN_CURS (1)
#define PARCURS (2)

int n, m;
int T = 1;
std::vector<int> G[MAX_N + 1];
std::vector<int> Gt[MAX_N + 1];

int culoare[MAX_N + 1]; // {0, 1, 2} <=> {nevizitat, in curs de parcurgere, parcurs complet}
int tfin[MAX_N + 1], tfin_top = 0;

std::ifstream in("ctc.in");
std::ofstream out("ctc.out");

std::stringstream ss;

void citeste();
void timpi(int x);
void dfs(int x, void (*proceseaza)(int));
void proceseaza(int x);

void citeste()
{
    in >> n >> m;
    for (int i = 0; i < m; i++) {
        int x, y;
        in >> x >> y;

        G[x].push_back(y);

        // Reprezint în memorie graful transpus
        Gt[y].push_back(x);
    }
}

void timpi(int x)
{
    culoare[x] = IN_CURS;
    for (int i = 0; i < Gt[x].size(); i++) {
        if (culoare[Gt[x][i]] == NEVIZITAT) {
            timpi(Gt[x][i]);
        }
    }

    culoare[x] = PARCURS;
    tfin[tfin_top++] = x;
}

void dfs(int x, void (*proceseaza)(int))
{
    proceseaza(x);
    culoare[x] = IN_CURS;
    for (int i = 0; i < G[x].size(); i++) {
        if (culoare[G[x][i]] == NEVIZITAT) {
            dfs(G[x][i], proceseaza);
        }
    }
    culoare[x] = PARCURS;
}

void proceseaza(int x)
{
    ss << x << " ";
}


int main()
{
    citeste();

    for (int i = 1; i <= n; i++) {
        if (culoare[i] == NEVIZITAT) {
            timpi(i);
        }
    }

    memset(culoare + 1, NEVIZITAT, n * sizeof(int));


    #ifdef DEBUG
    for (int i = 1; i <= n; i++) {
        std::cout << culoare[i] << " ";
    }
    std::cout << "\n";

    for (int i = 0; i < tfin_top; i++) {
        std::cout << tfin[i] << " ";
    }
    std::cout << "\n";
    #endif

    int num_comp = 0;
    tfin_top--;
    while (tfin_top != -1) {
        if (culoare[tfin[tfin_top]] == NEVIZITAT) {
            num_comp++;
            dfs(tfin[tfin_top], proceseaza);
            ss << "\n";
        }
        tfin_top--;
    }

    out << num_comp << "\n";
    out << ss.str();

    return 0;
}