Cod sursa(job #2999681)

Utilizator victor_gabrielVictor Tene victor_gabriel Data 11 martie 2023 12:01:47
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

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

const int DIM = 100001;
struct edge {
    int x, y;
    bool vis;
} edges[5 * DIM];
vector<int> l[DIM], cicle;
stack<int> st;
int n, m, x, y;

int main() {
    fin >> n >> m;
    for (int i = 1; i <= m; i++) {
        fin >> x >> y;
        edges[i] = { x, y, false };
        l[x].push_back(i);
        l[y].push_back(i);
    }

    for (int i = 1; i <= n; i++) {
        if (l[i].size() % 2 != 0) {
            fout << -1;
            return 0;
        }
    }

    st.push(1);
    while (!st.empty()) {
        int node = st.top();
        bool ok = false;

        while (!l[node].empty()) {
            int edge = l[node].back();
            l[node].pop_back();
            if (!edges[edge].vis) {
                int adjNode = edges[edge].x;
                if (edges[edge].y != node)
                    adjNode = edges[edge].y;
                st.push(adjNode);
                edges[edge].vis = true;
                ok = true;
                break;
            }
        }

        if (!ok) {
            cicle.push_back(node);
            st.pop();
        }
    }

    if (cicle.size() != m + 1) {
        fout << -1;
        return 0;
    }
    for (int i = 0; i < cicle.size() - 1; i++)
        fout << cicle[i] << ' ';

    return 0;
}