Cod sursa(job #2767543)

Utilizator SabailaCalinSabaila Calin SabailaCalin Data 6 august 2021 17:17:42
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.54 kb
#include <algorithm>
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#define SZ(x) ((int) (x).size())
using namespace std;

ifstream f ("ciclueuler.in");
ofstream g ("ciclueuler.out");

const int NMAX = 100005, MMAX = 500005;

vector<int> G[NMAX];

bool usedEdge[MMAX];
int from[MMAX], to[MMAX];
int n, m;

void PrintGraph()
{
    for (int i = 1; i <= n; i++)
    {
        cout << "Node " << i << " : ";
        for (int j = 0; j < G[i].size(); j++)
        {
            cout << G[i][j] << " ";
        }
        cout << "\n";
    }
}

int main() {
        f >> n >> m;

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

    //PrintGraph();

    for (int i = 1; i <= n; ++i) {
        if (G[i].size() % 2 == 1) {
            g << "-1\n";
            return 0;
        }
    }

    vector<int> ans;

    stack <int> stk;
    stk.push(1);
    while (!stk.empty()) {
        int node = stk.top();
        if (!G[node].empty()) {
            int e = G[node].back();
            G[node].pop_back();
            if (!usedEdge[e]) {
                usedEdge[e] = true;
                int to = ::from[e] ^ ::to[e] ^ node;
                stk.push(to);
            }
        } else {
            stk.pop();
            ans.push_back(node);
        }
    }

    for (int i = 0; i < SZ(ans) - 1; ++i) {
        g << ans[i] << ' ';
    }
    g << '\n';

}