Cod sursa(job #2692643)

Utilizator mex7Alexandru Valentin mex7 Data 3 ianuarie 2021 13:25:27
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <bits/stdc++.h>
#define ll long long
#define cin fin
#define cout fout
using namespace std;
	
ifstream fin("ciclueuler.in");
ofstream fout("ciclueuler.out");
int n, m, x, y;
vector <int> adj[100004];
pair <int, int> edge[500005];
bitset <500005> reached;
 
int main() {
	cin >> n >> m;
	for (int i = 1; i <= m; i++) {
		cin >> x >> y;
		adj[x].push_back(i);
		adj[y].push_back(i);
		edge[i] = make_pair(x, y);
	}
 
	for (int i = 1; i <= n; i++) 
		if (!adj[i].empty() && adj[i].size() % 2) {
			cout << -1;
			return 0;
		}
 
	stack <int> currNode;
	vector <int> result;
	currNode.push(1);
	while (!currNode.empty()) {
		int node = currNode.top();
 
		if (adj[node].empty()) {
			result.push_back(node);
			currNode.pop();
		} else {
			int edgeInd = adj[node].back();
			adj[node].pop_back();
			
			if (!reached[edgeInd]) {
				int nextNode;
				reached[edgeInd] = 1;

				if (node == edge[edgeInd].first)
					nextNode = edge[edgeInd].second;
				else
					nextNode = edge[edgeInd].first;


				currNode.push(nextNode);
			}
		}
	}
 
	for (int i = 0; i < result.size() - 1; i++)
		cout << result[i] << ' ';
 
	return 0;
}