Cod sursa(job #1237305)

Utilizator CosminRusuCosmin Rusu CosminRusu Data 3 octombrie 2014 19:25:17
Problema Componente biconexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.19 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; }

Graph g;
int N, M;
int dflevel[MAXN], lowlink[MAXN];
stack <pair<int, int> > st;
vector <set<int> > BCC;

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

void dfs(int node, int father, int actlevel) {
    dflevel[node] = lowlink[node] = actlevel;
    for(It it = g[node].begin(), fin = g[node].end(); it != fin ; ++ it) {
        if(*it == father)
            continue;
        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])
                extractBCC(node, *it);
        } else
            lowlink[node] = min(lowlink[node], dflevel[*it]);
    }
}

int main() {
    fin >> N >> M;
    while(M--) {
        int x, y;
        fin >> x >> y;
        g[x].push_back(y);
        g[y].push_back(x);
    }
    dfs(1, 0, 1);
    fout << BCC.size() << '\n';
    for(auto comp: BCC) {
        for(auto it:comp)
            fout << it << ' ';
        fout << '\n';
    }
    fin.close();
    fout.close();
    return 0;
}