Cod sursa(job #2803819)

Utilizator Tudor_PascaTudor Pasca Tudor_Pasca Data 20 noiembrie 2021 14:34:21
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.61 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <bitset>

using namespace std;

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

const int N_MAX = 1e5 + 10;
const int M_MAX = 5e5 + 10;

int n, m;
int pos[N_MAX];
pair<int, int> edge[M_MAX];
bitset<M_MAX> del;
vector<int> adj[N_MAX], ans;

bool euler()
{
    for(int i = 1; i <= n; i++)
        if(adj[i].size() % 2 != 0)
            return 0;
    return 1;
}

int findEdge(int node)
{
    for(int i = pos[node]; i < adj[node].size(); i++)
    {
        int x = adj[node][i];
        if(!del[x])
        {
            del[x] = 1;
            pos[node] = i + 1;
            return x;
        }
    }
    return -1;
}

void solve()
{
    stack<int> s;
    s.push(1);
    while(!s.empty())
    {
        int node = s.top();
        int nextEdge = findEdge(node);
        //cout << node << ' ' << nextEdge << '\n';
        if(nextEdge == -1)
        {
            s.pop();
            ans.push_back(node);
        }
        else
        {
            int nextNode = edge[nextEdge].first + edge[nextEdge].second - node;
            s.push(nextNode);
        }
    }
}

int main()
{
    in >> n >> m;
    for(int i = 0; i < m; i++)
    {
        int x, y;
        in >> x >> y;
        edge[i] = {x, y};
        adj[x].push_back(i);
        adj[y].push_back(i);
    }

    if(!euler())
    {
        out << "-1\n";
        return 0;
    }

    solve();

    for(int i = 0; i < ans.size() - 1; i++)
        out << ans[i] << ' ';
    out << '\n';

    return 0;
}