Cod sursa(job #3349013)

Utilizator tudorhTudor Horobeanu tudorh Data 24 martie 2026 23:01:04
Problema Ciclu Eulerian Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <bits/stdc++.h>
#define pii pair<int,int>
#define pb push_back
#define ll long long


using namespace std;

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

const int nmax = 1e5, mmax = 5e5;

vector<pii>v[nmax + 1];
bool used[mmax + 1];

vector<int>ans;

void trim (int nod) {
    while (!v[nod].empty() && used[v[nod].back().second])
        v[nod].pop_back();
}

void euler (int nod) {
    stack<int>stk;
    stk.push (nod);
    while (!stk.empty() ) {
        nod = stk.top();
        trim (nod);
        if (!v[nod].empty() ) {
            int t = v[nod].back().first, i = v[nod].back().second;
            used[i] = 1;
            trim (nod);
            stk.push (t);
        }
        else{
            stk.pop();
            ans.pb(nod);
        }
    }


    ans.pb (nod);
}

int main() {

    int n, m;
    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        int st, dr;
        fin >> st >> dr;
        v[st].pb ({dr, i});
        v[dr].pb ({st, i});
    }
    euler (1);
    if (ans.size() != m + 1 || ans.back() != ans[0]) {
        fout << -1;
        return 0;
    }
    ans.pop_back();
    for (int i : ans)
        fout << i << ' ';
    return 0;
}