Cod sursa(job #881956)

Utilizator cristian.ion94Ion Cristian cristian.ion94 Data 18 februarie 2013 19:44:37
Problema Ciclu Eulerian Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 2.31 kb
#include <fstream>
#define DMAX 1001
using namespace std;

struct Node
{
    int vf;
    struct Node * p_next;
};

typedef struct Node * List;

List c1,c2,sfc1,sfc2;

int G[DMAX][DMAX];
int d[DMAX], vis[DMAX];

int n,m, ind;

void init();

int cicle(int x, List & c, List & sfc);
void build_cicle();

void dfs(int x);
int conex();

int eulerian();

void show_cicle()
{
    ofstream fout("ciclueuler.out");

    for(List p = c1; p;p = p->p_next)
    {
        fout << p->vf << ' ';
    }
    fout << '\n';

    fout.close();
}

int main()
{
    init();

    if(!eulerian())
    {
        ofstream fout("ciclueuler.out");
        fout << -1;
        fout.close();
        return 0;
    }

    build_cicle();
    show_cicle();

    return 0;
}

void init()
{
    ifstream fin("ciclueuler.in");

    fin >> n >> m;

    int i,x,y;
    for(i = 1; i <= m; i++)
    {
        fin >> x >> y;
        G[x][y] = 1;
        G[y][x] = 1;
        d[x]++;
        d[y]++;
    }

    fin.close();
}

void dfs(int x)
{
    vis[x] = 1;
    for(int i = 1; i <= n; i++)
        if(G[x][i] == 1 && !vis[i])
            dfs(i);
}

int conex()
{
    dfs(1);
    for(int i = 1; i <= n; i++)
        if(vis[i] == 0) return 0;
    return 1;
}

int eulerian()
{
    if(!conex()) return 0;

    for(int v = 1; v <= n; v++)
        if(d[v] % 2 == 1)
            return 0;
    return 1;
}

int cicle(int x, List & c, List & sfc)
{
    List p;
    int y, uvf, lg=0;

    p = new Node;
    p->vf = x;
    p->p_next = NULL;
    c = sfc = p;

    do
    {
        uvf = sfc->vf;

        //parcurg lista de adiacenta a lui y
        for(y = 1; !G[uvf][y]; y++);

        p = new Node;
        p->vf = y;
        p->p_next = NULL;

        sfc->p_next = p;
        sfc = p;
        lg++;
        G[uvf][y] = G[y][uvf] = false;
        d[y]--;
        d[uvf]--;

    }
    while(y != x);

    return lg;
}

void build_cicle()
{
    int x, total = 0;
    List p,q;

    for(x = 1; x <= n && !d[x]; x++);

    total = cicle(x, c1, sfc1);
    while(total < m)
    {
        for(p = c1; !d[p->vf]; p = p->p_next);

        total += cicle(p->vf, c2, sfc2);

        q = p->p_next;
        p->p_next = c2->p_next;
        sfc2->p_next = q;
    }
}