Cod sursa(job #766142)

Utilizator mi5humihai draghici mi5hu Data 10 iulie 2012 14:17:56
Problema Componente tare conexe Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 2.4 kb
#include <stdio.h>
#include <fstream>
#include <vector>
#include <set>
#include <stack>
using namespace std;

typedef struct {
    int index;
    int node;
    int lowlink;
    vector<int> edges;
    bool inStack;
} vertex;

int n, m, ind = 1;
vertex v[100001];
stack<vertex> S;
set< vector<int> > rez;

int min(int a, int b) {
    return a < b ? a : b;
}

void read_() {
    int source, dest;          
    ifstream fin("ctc.in");
    fin >> n >> m;
    for (int i = 0; i < m; i++) {
        fin >> source >> dest;
        v[source].edges.push_back(dest);
    }     
    fin.close();
}

int get_el() {
    int el = S.top().node;
    S.pop();
    v[el].inStack = false;
    return el;
}

void vertex_init(int poz) {
    v[poz].index = ind;
    v[poz].lowlink = ind;
    ind++;
    v[poz].inStack = true;
    S.push(v[poz]);
}

void dfs_tarj(int poz) {
     
    vertex_init(poz);    
    
    vector<int>::iterator it;
    for (it = v[poz].edges.begin(); it != v[poz].edges.end(); it++) {
        if (v[*it].index == 0) {
            dfs_tarj(*it);
            v[poz].lowlink = min(v[poz].lowlink, v[*it].lowlink);                    
        } else if (v[*it].inStack == true) {
            v[poz].lowlink = min(v[poz].lowlink, v[*it].index);       
        }
    } 
     
    if (v[poz].lowlink == v[poz].index) {
       vector<int> ctc;
       int nou = get_el();       
       ctc.push_back(nou);
       while (v[poz].node != nou) {
           nou = get_el();  
           ctc.push_back(nou);                
       }    
       rez.insert(ctc);                
    }      
}

void tarjan() {
    for (int i = 1; i <= n; i++) {
        if (v[i].index == 0) {
           dfs_tarj(i);           
        }
    }
}

void write_() {
     ofstream fout("ctc.out");
     set< vector<int> >::iterator set_it;
     vector<int>::iterator vect_it;
     
     fout << rez.size() << endl; 
     for (set_it = rez.begin(); set_it != rez.end(); set_it++) {
         vector<int> ctc = *set_it;
         for (vect_it = ctc.begin(); vect_it != ctc.end(); vect_it++) {
             fout << *vect_it << " ";
         } 
         fout << endl;
     }
     
     fout.close();
}

void init() {
     for (int i = 1; i <= n; i++) {
         v[i].node = i;
     }     
}

int main() {        
    read_();
    init();
    tarjan();
    write_();    
    return 0; 
}