Cod sursa(job #2022840)

Utilizator Horia14Horia Banciu Horia14 Data 17 septembrie 2017 14:51:25
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.94 kb
#include<cstdio>
#include<vector>
#include<stack>
#include<cstdlib>
#define MAX_N 100000
using namespace std;

struct node
{
    int val;
    node* next;
};

FILE *fout = fopen("ciclueuler.out","w");
node* G[MAX_N+1];
stack<int>S;
vector<int>sol;
int degree[MAX_N+1], n, m;

inline void insertNode(int x, int y)
{
    node* elem = (node*)malloc(sizeof(node));
    elem->val = y;
    elem->next = G[x];
    G[x] = elem;
}

void Read()
{
    int x, y;
    FILE *fin = fopen("ciclueuler.in","r");
    fscanf(fin,"%d%d",&n,&m);
    for(int i=1; i<=m; i++)
    {
        fscanf(fin,"%d%d",&x,&y);
        insertNode(x,y);
        insertNode(y,x);
        degree[x]++;
        degree[y]++;
    }
    fclose(fin);
}

node* deleteNode(node* head, int x)
{
    if(head->val == x)
    {
        node* p = head;
        head = head->next;
        free(p);
        return head;
    }
    else
    {
        node* p = head;
        while(p->next->val != x)
            p = p->next;
        node* q = p->next;
        p->next = p->next->next;
        free(q);
        return head;
    }
}

void Euler(int u)
{
    int v;
    S.push(u);
    while(!S.empty())
    {
        u = S.top();
        if(G[u] != NULL)
        {
            node* p = G[u];
            v = G[u]->val;
            G[u] = G[u]->next;
            free(p);
            G[v] = deleteNode(G[v], u);
            S.push(v);
        }
        else
        {
            S.pop();
            sol.push_back(u);
        }
    }
}

bool isEulerian()
{
    bool ok = true;
    for(int i=1; i<=n && ok; i++)
        if(degree[i] & 1)
            ok = false;
    return ok;
}

int main()
{
    Read();
    if(isEulerian())
    {
        Euler(1);
        for(int i=0; i<sol.size()-1; i++)
            fprintf(fout,"%d ",sol[i]);
        fprintf(fout,"\n");
    }
    else fprintf(fout,"-1\n");
    fclose(fout);
    return 0;
}