Cod sursa(job #3146637)

Utilizator patrick_burasanPatrick Burasan patrick_burasan Data 21 august 2023 23:12:41
Problema Ciclu Eulerian Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

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

int const NMAX = 100005, MMAX = 500005;
int n, m, u, v, node, edge, newNode, from[MMAX], to[MMAX];
vector < int > ans, adj[NMAX];
bool usedEdge[NMAX];

int main() {
    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        fin >> u >> v;
        adj[u].push_back(i);
        adj[v].push_back(i);
        from[i] = u;
        to[i] = v;
    }

    for (int i = 1; i <= n; i++)
        if ((int)adj[i].size() & 1) {
            fout << "-1\n";
            return 0;
        }
    
    stack < int > st;
    st.push(1);
    while (!st.empty()) {
        node = st.top();
        if (adj[node].size()) {
            edge = adj[node].back();
            adj[node].pop_back();
            if (!usedEdge[edge]) {
                usedEdge[edge] = true;
                newNode = node ^ from[edge] ^ to[edge];
                st.push(newNode);
            }
        } else {
            st.pop();
            ans.push_back(node);
        }
    }

    for (auto it : ans)
        fout << it << ' ';
    fout << '\n';
    fin.close();
    fout.close();
    return 0;
}