Cod sursa(job #3001497)

Utilizator victor_gabrielVictor Tene victor_gabriel Data 13 martie 2023 18:38:25
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <fstream>
#include <vector>
#include <stack>

using namespace std;

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

const int DIM = 100010;
const int EDGE_DIM = 500010;

int n, m, x, y;
int deg[DIM], lastEdge[DIM];
vector<pair<int, int>> l[DIM];
vector<int> sol;
stack<int> st;
bool vis[EDGE_DIM];

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

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

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

        if (deg[node] == 0) {
            st.pop();
            sol.push_back(node);
            continue;
        }

        for (int i = lastEdge[node]; i < l[node].size(); i++) {
            int edge = l[node][i].first;
            int adjNode = l[node][i].second;
            if (!vis[edge]) {
                vis[edge] = true;
                st.push(adjNode);
                deg[node]--, deg[adjNode]--;
                lastEdge[node] = i + 1;
                break;
            }
        }
    }

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

    return 0;
}