Cod sursa(job #2200839)

Utilizator Mihai7Gheoace Mihai Mihai7 Data 2 mai 2018 19:25:16
Problema Componente tare conexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.24 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <bitset>
using namespace std;

#define MAXN  100005
 
vector <int> Go[MAXN];  // lista de adiacenta pentru graf 
vector <int> Gi[MAXN];  // lista de adiacenta pentru graf transpus
vector <int> G[MAXN];  // lista de componente tare conexe
 
void read_in(vector <int>* Go, vector <int>* Gi, int& n)
{
    ifstream in("ctc.in");
    int cnt_edges, x, y;
 
    in >> n;
    for (in >> cnt_edges; cnt_edges > 0; -- cnt_edges) {
        in >> x >> y;
        x --, y --;  // be careful
        Go[x].push_back(y);
        Gi[y].push_back(x);
    }
    in.close();
}
 
vector <int> discovered;  // salveaza varfurile in ordinea inversa gasirii lor
// e.g. in discovered.back() e primul gasit de DFP
bitset <MAXN> used;  // vectori de vizitati
 
void DFP(const int n, vector <int>* G)  // Marcheaza cu +
{  // DFS cu Plus = DFP
    vector <int>::iterator it;
    used[n] = true;
    for (it = G[n].begin(); it != G[n].end(); ++ it)
        if (used[*it] == false)
            DFP(*it, G);
    discovered.push_back(n);
}
 
vector <int> where;
   // 
void DFM(const int n, vector <int>* G, const int which)  // Marcheaza cu -
{  // DFS cu Minus = DFM
    vector <int>::iterator it;
    where[n] = which;
    for (it = G[n].begin(); it != G[n].end(); ++ it)
        if (where[*it] == -1)
            DFM(*it, G, which);
}
 
void print_out(const vector <int>* G, const int n)
{
    ofstream out("ctc.out");
    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;
    read_in(Go, Gi, n);
    std::ios::sync_with_stdio(false);  // pt nu folosesc stdio.
    
    for (int i = 0; i < n; ++ i)
        if (used[i] == false)
            DFP(i, Go);
 
    where.resize(n);
    where.assign(where.size(), -1);
    int count = 0;
    for (; discovered.size(); discovered.pop_back())
        if (where[discovered.back()] == -1) {
            DFM(discovered.back(), Gi, count);
            count ++;
        }
    for (int i = 0; i < n; ++ i)
        G[where[i]].push_back(i);
 
    print_out(G, count);
 
    return 0;
}