Cod sursa(job #1362253)

Utilizator mirceadinoMircea Popoveniuc mirceadino Data 26 februarie 2015 11:17:55
Problema Componente biconexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.6 kb
#include<cstdio>
#include<string>
#include<vector>
#include<algorithm>
#include<bitset>

using namespace std;

#ifdef HOME
const string inputFile = "input.txt";
const string outputFile = "output.txt";
#else
const string problemName = "biconex";
const string inputFile = problemName + ".in";
const string outputFile = problemName + ".out";
#endif

const int NMAX = 100000 + 5;

int N, M, nr_cb;
vector<int> V[NMAX];
vector<int> S;
vector<int> C[NMAX];
int dad[NMAX];
int low[NMAX];
int lvl[NMAX];
bitset<NMAX> viz;

void get_biconex(int x, int y) {
    nr_cb++;

    while(S.back() != y) {
        C[nr_cb].push_back(S.back());
        S.pop_back();
    }

    C[nr_cb].push_back(x);
    C[nr_cb].push_back(y);

    S.pop_back();
}

void dfs(int x) {
    viz[x] = 1;

    for(auto y : V[x]) {
        if(y == dad[x])
            continue;

        if(!viz[y]) {
            dad[y] = x;
            low[y] = lvl[y] = lvl[x] + 1;
            S.push_back(y);

            dfs(y);

            if(low[y] >= lvl[x])
                get_biconex(x, y);

            low[x] = min(low[x], low[y]);
        }

        low[x] = min(low[x], lvl[y]);
    }
}

int main() {
    int i, x, y;

    freopen(inputFile.c_str(), "r", stdin);
    freopen(outputFile.c_str(), "w", stdout);

    scanf("%d%d", &N, &M);

    while(M--) {
        scanf("%d%d", &x, &y);
        V[x].push_back(y);
        V[y].push_back(x);
    }

    for(i = 1; i <= N; i++)
        if(!viz[i])
            dfs(i);

    printf("%d\n", nr_cb);

    for(i = 1; i <= nr_cb; i++) {
        for(auto x : C[i])
            printf("%d ", x);
        printf("\n");
    }

    return 0;
}