Cod sursa(job #1122622)

Utilizator visanrVisan Radu visanr Data 25 februarie 2014 19:23:25
Problema Componente biconexe Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.66 kb
#include <cstdio>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;

const int NMAX = 100010;

int N, M, X, Y, Level[NMAX], Low[NMAX];
stack<pair<int, int> > S;
vector<int> G[NMAX], CurrentComp;
vector<vector<int> > Comp;

void GetBC(int X, int Y)
{
    CurrentComp.clear();
    pair<int, int> Now;

    do
    {
        Now = S.top();
        S.pop();
        CurrentComp.push_back(Now.second);
    }while(Now.first != X && Now.second != Y);

    CurrentComp.push_back(Now.first);
    Comp.push_back(CurrentComp);
}

void DFS(int Node, int Father)
{
    Low[Node] = Level[Node];
    for(vector<int> :: iterator it = G[Node].begin(); it != G[Node].end(); ++ it)
    {
        if(*it == Father) continue;
        if(!Level[*it])
        {
            Level[*it] = Level[Node] + 1;
            S.push(make_pair(Node, *it));
            DFS(*it, Node);
            Low[Node] = min(Low[Node], Low[*it]);
            if(Low[*it] >= Level[Node]) GetBC(Node, *it);
        }else Low[Node] = min(Low[Node], Low[*it]);
    }
}

int main()
{
    freopen("biconex.in", "r", stdin);
    freopen("biconex.out", "w", stdout);

    scanf("%i %i", &N, &M);
    for(int i = 1; i <= M; ++ i)
    {
        scanf("%i %i", &X, &Y);
        G[X].push_back(Y);
        G[Y].push_back(X);
    }

    for(int i = 1; i <= N; ++ i)
        if(!Level[i])
        {
            Level[i] = 1;
            DFS(i, 0);
        }

    printf("%i\n", Comp.size());
    for(int i = 0; i < Comp.size(); ++ i)
    {
        for(int j = 0; j < Comp[i].size(); ++ j)
            printf("%i ", Comp[i][j]);
        printf("\n");
    }
}