Cod sursa(job #2870533)

Utilizator popoviciAna16Popovici Ana popoviciAna16 Data 12 martie 2022 13:43:17
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;

ifstream fin ("ciclueuler.in");
ofstream fout ("ciclueuler.out");

struct elmuch
{
    int x, y;
} much[500001];

vector <int> v[100001];
bool fol[500001];
int s[500001], rasp[500001];

void dfs (int x)
{
    fol[x] = 1;
    int i, xv;
    for (i = 0; i<v[x].size(); i++)
    {
        xv = x ^ much[v[x][i]].x ^ much[v[x][i]].y;
        if (fol[xv] == 0)
            dfs (xv);
    }
}

int main()
{
    int n, m, i, x, y;

    fin >> n >> m;
    for (i = 1; i<=m; i++)
    {
        fin >> x >> y;
        much[i] = {x, y};
        v[x].push_back (i);
        v[y].push_back (i);
    }

    dfs (1);
    for (i = 1; i<=n; i++)
    {
        if (fol[i] == 0 || v[i].size() % 2 == 1)
        {
            fout << -1;
            return 0;
        }
        fol[i] = 0;
    }

    s[0] = s[1] = 1;
    while (s[0] > 0)
    {
        x = s[s[0]];

        if (v[x].empty() == 0)
        {
            y = v[x].back();
            v[x].pop_back();

            if (fol[y] == 0)
            {
                fol[y] = 1;
                s[++s[0]] = x ^ much[y].x ^ much[y].y;
            }
        }
        else
        {
            rasp[++rasp[0]] = x;
            s[0]--;
        }
    }

    for (i = 1; i<rasp[0]; i++)
        fout << rasp[i] << ' ';
    return 0;
}