Cod sursa(job #1165881)

Utilizator poptibiPop Tiberiu poptibi Data 2 aprilie 2014 23:55:20
Problema Componente biconexe Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.71 kb
#include <cstdio>
#include <cstdlib>
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;

const int NMAX = 100010;

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

void GetComp(int X, int Y)
{
    vector<int> CrtComp;
    pair<int, int> Now;

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

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)
        {
            if(Level[*it] == 0)
            {
                S.push(make_pair(Node, *it));
                Level[*it] = Level[Node] + 1;
                DFS(*it, Node);
                Low[Node] = min(Low[Node], Low[*it]);
                if(Low[*it] >= Level[Node])
                    GetComp(Node, *it);
            }else Low[Node] = min(Low[Node], Level[*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");
    }
}