Cod sursa(job #2845805)

Utilizator TudosieRazvanTudosie Marius-Razvan TudosieRazvan Data 8 februarie 2022 13:24:38
Problema Ciclu Eulerian Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <fstream>
#include <algorithm>
#include <climits>
#include <vector>
#include <queue>
#include <stack>
#include <unordered_map>
#define NMAX 100003
using namespace std;


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

int n, m;
int grad[NMAX];
unordered_map<int, int>hashMap[NMAX];

int main()
{
    fin >> n >> m;
    for (int i = 1; i <= m; i++)
    {
        int x, y;
        fin >> x >> y;
        grad[x]++;
        grad[y]++;
        hashMap[x].insert({ i,y });
        hashMap[y].insert({ i,x });
    }

    for (int i = 1; i <= n; i++)
    {
        if (grad[i]% 2 == 1)
        {
            fout << "-1";
            return 0;
        }

    }

    stack<int>stiv;
    stiv.push(1);
    vector<int>sol;
    while (!stiv.empty())
    {
        int nod = stiv.top();
        if (hashMap[nod].size() == 0) {
            sol.push_back(nod);
            stiv.pop();
        }
        else {
            auto itr = hashMap[nod].begin();
            int nd = itr->second;
            stiv.push(nd);
            int cod = itr->first;
           
            hashMap[nd].erase(cod);
            hashMap[nod].erase(cod);
        }
    }
    if (sol.size() != m + 1)
    {
        fout << "-1";
        return 0;
    }
    for (int i = 0; i < sol.size() - 1; i++)
    {
        fout << sol[i] << " ";
    }
    return 0;
}