Cod sursa(job #2869842)

Utilizator qweryclujRadu Alexandru qwerycluj Data 11 martie 2022 21:13:22
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.53 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

//tinem indexi de muchie
vector<int> G[100005];
int to[500004];
int from[500004];
bool viz[500004];

vector<int> sol;
int n, m;

int main()
{
    ifstream fin("ciclueuler.in");
    ofstream fout("ciclueuler.out");
    fin >> n >> m;

    int x, y;
    for (int i = 0; i < m; i++)
    {
        fin >> x >> y;
        G[x].push_back(i);
        G[y].push_back(i);
        to[i] = y;
        from[i] = x;
    }

    //verif grad
    for (int i = 1; i <= n; i++)
    {
        if (G[i].size() % 2 == 1)
        {
            fout << "-1\n";
            fout.close();
            fin.close();
            return 0;
        }
    }

    vector<int> vec;
    vec.push_back(1);
    int cache;
    //forma mai interesanta de  a scrie un dfs si a pune toate elementele intr'o coada
    while (!vec.empty())
    {
        int nod = vec.back();
        if (!G[nod].empty())
        {
            int vit = G[nod].back();
            G[nod].pop_back();
            if (!viz[vit])
            {
                // se bazeaza pe proprietatile XOR: x ^ x = 0 si 0 ^ x = x
                cache = to[vit] ^ from[vit] ^ nod;
                viz[vit] = true;
                vec.push_back(cache);
            }
        }
        else
        {
            vec.pop_back();
            sol.push_back(nod);
        }
    }

    for (int i = 0; i < sol.size() - 1; i++)
    {
        fout << sol[i] << " ";
    }
}