Cod sursa(job #1126796)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 27 februarie 2014 09:47:42
Problema Componente biconexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.22 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <bitset>
#include <string.h>
#include <algorithm>
#include <iomanip>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <set>
#include <map>
#include <string>
#include <queue>
#include <stack>

using namespace std;

const char infile[] = "biconex.in";
const char outfile[] = "biconex.out";

ifstream fin(infile);
ofstream fout(outfile);

const int MAXN = 100005;
const int oo = 0x3f3f3f3f;

typedef vector<int> Graph[MAXN];
typedef vector<int> :: iterator It;

const inline int min(const int &a, const int &b) { if( a > b ) return b;   return a; }
const inline int max(const int &a, const int &b) { if( a < b ) return b;   return a; }
const inline void Get_min(int &a, const int b)    { if( a > b ) a = b; }
const inline void Get_max(int &a, const int b)    { if( a < b ) a = b; }

int N, M, K;
int lowLink[MAXN], dfLevel[MAXN];
stack <pair<int, int> > st;
set<set<int> > BCC;
Graph G;

void extractCompBiconex(int x, int y) {
    int Tx, Ty;
    set <int> actComp;
    do {
        Tx = st.top().first;
        Ty = st.top().second;
        st.pop();
        actComp.insert(Tx);
        actComp.insert(Ty);
    } while(Tx != x || Ty != y);
    BCC.insert(actComp);
}

void DFs(int Node, int Father, int actLevel) {
    dfLevel[Node] = lowLink[Node] = ++ K;
    for(It it = G[Node].begin(), fin = G[Node].end(); it != fin ; ++ it) {
        if(!dfLevel[*it]) {
            st.push(make_pair(Node, *it));
            DFs(*it, Node, actLevel + 1);
            lowLink[Node] = min(lowLink[Node], lowLink[*it]);
            if(lowLink[*it] >= dfLevel[Node]) {
                extractCompBiconex(Node, *it);
            }
        } else {
            lowLink[Node] = min(lowLink[Node], dfLevel[*it]);
        }
    }
}

int main() {
    fin >> N >> M;
    for(int i = 1 ; i <= M ; ++ i) {
        int x, y;
        fin >> x >> y;
        G[x].push_back(y);
        G[y].push_back(x);
    }
    DFs(1, 1, 1);
    fout << BCC.size() << '\n';
    for(auto comp : BCC) {
        for(auto it : comp)
            fout << it << ' ';
        fout << "\n";
    }
    fin.close();
    fout.close();
    return 0;
}