Cod sursa(job #2979703)

Utilizator 100pCiornei Stefan 100p Data 15 februarie 2023 19:24:56
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.69 kb
#include <bits/stdc++.h>

#define MAX 100000
#define EMAX 500000

using namespace std;

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


#define FILES freopen("ciclueuler.in","r",stdin);\
              freopen("ciclueuler.out","w",stdout);

int n, m, a, b, imp, st, s[EMAX + 5];
vector <pair<int,int>> graph[MAX + 5];
stack<int> dfs_stack;
vector<int> ans;
bool check[EMAX + 5];

void dfs()
{
    while(!dfs_stack.empty())
    {
        s[++s[0]] = dfs_stack.top();

        int node = dfs_stack.top();
        bool ok = 0;
        while(graph[node].size() > 0)
        {
            int nextNode = graph[node].back().first, edge = graph[node].back().second;

            if(!check[edge])
            {
                check[edge] = 1;
                dfs_stack.push(nextNode);
                graph[node].pop_back();
                ok = 1;
                break;
            }
            else
                graph[node].pop_back();
        }

        if(ok)
            continue;

        ans.push_back(s[s[0]--]);
        dfs_stack.pop();
    }
}

signed main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    FILES
    cin >> n >> m;
    for(int i = 1; i <= m; ++i)
    {
        cin >> a >> b;
        graph[a].push_back({b, i});
        graph[b].push_back({a, i});
    }

    st = 1;
    for(int i = 1; i <= n; ++i)
    {
        if(graph[i].size() % 2)
            imp++, st = i;
    }

    if(imp)
    {
        cout << -1;
        exit(0);
    }
    dfs_stack.push(1);
    dfs();
    reverse(ans.begin(), ans.end());
    ans.pop_back();
    for(auto i : ans)
        cout << i << ' ';
}