Cod sursa(job #3223751)

Utilizator DobraVictorDobra Victor Ioan DobraVictor Data 13 aprilie 2024 15:14:41
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.29 kb
#include <iostream>
#include <fstream>
#include <stdint.h>
#include <vector>

const int32_t MAX_N = 100000;
const int32_t MAX_M = 500000;

struct Edge {
	int32_t x, y;
};

Edge edges[MAX_M];
std::vector<int32_t> adj[MAX_N];
int32_t stack[MAX_M + 1], top = 0;
int32_t res[MAX_M + 1], resLen = 0;
int main() {
	std::ifstream fin("ciclueuler.in");
	std::ofstream fout("ciclueuler.out");

	int32_t n, m;
	fin >> n >> m;

	for(int32_t i = 0; i != m; ++i) {
		int32_t x, y;
		fin >> x >> y;
		--x; --y;

		adj[x].push_back(i);
		adj[y].push_back(i);
		edges[i] = { x, y };
	}

	for(int32_t i = 0; i != n; ++i) {
		if(adj[i].size() & 1) {
			fout << "-1\n";

			fin.close();
			fout.close();

			return 0;
		}
	}

	stack[top++] = 0;
	while(top) {
		int32_t node = stack[top - 1];

		if(!adj[node].empty()) {
			int32_t edge = adj[node].back();
			adj[node].pop_back();

			if(edges[edge].x != -1) {
				int32_t next;
				if(node == edges[edge].x) {
					next = edges[edge].y;
				} else {
					next = edges[edge].x;
				}
				edges[edge].x = -1;

				stack[top++] = next;
			}
		} else {
			res[resLen++] = stack[top - 1];
			--top;
		}
	}

	for(int32_t i = 0; i != resLen - 1; ++i)
		fout << (res[i] + 1) << ' ';

	fin.close();
	fout.close();

	return 0;
}