Cod sursa(job #844229)

Utilizator vendettaSalajan Razvan vendetta Data 28 decembrie 2012 22:40:57
Problema Componente biconexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.6 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include <set>
#include <queue>
#include <deque>

using namespace std;

ifstream f("biconex.in");
ofstream g("biconex.out");

#define nmax 100005
#define ll long long

int n, m, t[nmax], Min[nmax], nv[nmax];
bool viz[nmax];
vector<int> gf[nmax], Comp[nmax];
int cnt;
deque< pair<int,int> > dq;

void citeste(){
    f >> n >> m;
    int x, y;
    for(int i=1; i<=m; ++i){
        f >> x >> y;
        gf[x].push_back( y );
        gf[y].push_back(x);
    }
}

void dfs(int nod){
    viz[nod] = 1;
    for(int i=0; i<gf[nod].size(); ++i){
        int vc = gf[nod][i];
        if (viz[vc] == 0){
            t[vc] = nod;
            nv[vc] = nv[nod] + 1;
            Min[vc] = nv[vc];
            dq.push_back( make_pair( nod, vc ) );
            dfs(vc);
            Min[nod] = min(Min[nod], Min[vc]);
            if (Min[vc] >= nv[nod]){//daca nod e nod critic
                ++cnt;// apare o noua componenta
                int X = dq.back().first; int Y = dq.back().second;
                dq.pop_back();
                while (( X != nod || Y != vc ) && (X!=vc || Y!=nod) ){
                    //cout << X << " " << Y << " " << nod << " " << vc << "\n";
                    Comp[cnt].push_back(X); Comp[cnt].push_back(Y);
                    //if (dq.size() == 0) break;// nu o sa intre niciodata (cred)
                    X = dq.back().first; Y = dq.back().second;
                    dq.pop_back();
                }
                //cout << X << " " << Y << " " << nod << " " << vc << "\n";
                Comp[cnt].push_back(X); Comp[cnt].push_back(Y);
            }
        }else{//ma folosesc de o muchie de intoarcere
            if (t[nod] != vc){// daca nu e tatal lui nod
                Min[nod] = min(Min[nod], nv[vc]);
            }
        }
    }
}

void rezolva(){
    // o comp conexa e o comp ce nu contine noduri critice;

    for(int i=1; i<=n; ++i){// nu zice ca e graf conex(in enunt)
        if (viz[i] == 0){
            dfs(i);
        }
    }

    cout << cnt << "\n";
    g << cnt << "\n";
    for(int i=1; i<=cnt; ++i){
        sort(Comp[i].begin(), Comp[i].end());
        for(int j=1; j<Comp[i].size(); ++j){
            if (Comp[i][j-1] != Comp[i][j])
            cout << Comp[i][j-1] << " ",
            g << Comp[i][j-1] << " ";
        }
        cout << Comp[i][ Comp[i].size()-1 ] << " ",
        g << Comp[i][ Comp[i].size()-1 ] << " ";
        cout << "\n";
        g << "\n";
    }
}

int main(){
    citeste();
    rezolva();

    f.close();
    g.close();

    return 0;
}