Cod sursa(job #2840125)

Utilizator rapidu36Victor Manz rapidu36 Data 27 ianuarie 2022 09:51:16
Problema Ciclu Eulerian Scor 50
Compilator c-64 Status done
Runda Arhiva educationala Marime 2.31 kb
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define N 100000
#define M 200000

typedef struct
{
    int muc, urm;
} element;

typedef struct
{
    int x, y;
} muchie;

muchie e[M+1];
bool stearsa[M+1], viz[N+1];
int lst[N+1], n, m, nr, nce, stiva[N+1], d[N+1], ce[M+2];
element v[2*M+1];

void adauga(int x, int muc)
{//adauga pe y in lista de adiacenta a lui x
    v[++nr].muc = muc;
    v[nr].urm = lst[x];
    lst[x] = nr;
}

void push(int *pvf, int val)
{
    stiva[++(*pvf)] = val;
}

void pop(int *pvf)
{
    --(*pvf);
}

bool empty(int vf)
{
    return (vf == 0);
}

int prima_muchie_nestearsa(int x)
{
    while (lst[x] != 0 && stearsa[v[lst[x]].muc])//caut primul vecin al lui x cu cc nul
    {
        lst[x] = v[lst[x]].urm;
    }
    if (lst[x] != 0)
    {
        return v[lst[x]].muc;
    }
    return 0;
}

int celalalt_varf(muchie muc, int x)
{
    return (muc.x + muc.y - x);
}

void euler(int x)
{
    int vf_stiva = 0;
    push(&vf_stiva, x);
    while (!empty(vf_stiva))
    {
        x = stiva[vf_stiva];
        int i_e = prima_muchie_nestearsa(x);
        if (i_e == 0)///ne-am blocat in x (nu mai exista muchii incidente cu el nefolosite)
        {
            viz[x] = true;
            pop(&vf_stiva);
            ce[++nce] = x;
        }
        else
        {
            stearsa[i_e] = true;
            push(&vf_stiva, celalalt_varf(e[i_e], x));///adaug in stiva cealalta extremitate a muchiei
        }
    }
}

bool toate_gradele_pare()
{
    for (int i = 1; i <= n; i++)
    {
        if (d[i] % 2 != 0 || !viz[i])
        {
            return false;
        }
    }
    return true;
}

int main()
{
    FILE *in, *out;
    in = fopen("ciclueuler.in", "r");
    out = fopen("ciclueuler.out", "w");
    fscanf(in, "%d%d", &n, &m);
    for (int i = 1; i <= m; i++)
    {
        int x, y;
        fscanf(in, "%d%d", &x, &y);
        ++d[x];
        ++d[y];
        e[i] = (muchie){x, y};
        adauga(x, i);
        adauga(y, i);
    }
    euler(1);
    if (!toate_gradele_pare())
    {
        fprintf(out, "-1");
    }
    else
    {
        for (int i = 1; i < nce; i++)
        {
            fprintf(out, "%d ", ce[i]);
        }
    }

    fclose(in);
    fclose(out);
    return 0;
}