Cod sursa(job #3350517)

Utilizator DobraVictorDobra Victor Ioan DobraVictor Data 8 aprilie 2026 23:02:46
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.64 kb
#include <iostream>
#include <fstream>
#include <stdint.h>

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

int32_t n, m;
int32_t adjStarts[MAX_N], adjCounts[MAX_N];
int32_t adjNexts[MAX_M << 1], edgeSums[MAX_M];
int32_t stack[MAX_M + 1], top = 0;
int32_t cycle[MAX_M + 1], cycleLen = 0;

void ReadGraph(std::istream& fin) {
	fin >> n >> m;

	for(int32_t i = 0; i != n; ++i)
		adjStarts[i] = -1;
	for(int32_t i = 0; i != m; ++i) {
		int32_t node1, node2;
		fin >> node1 >> node2;
		--node1; --node2;

		++adjCounts[node1];
		++adjCounts[node2];
		edgeSums[i] = node1 + node2;

		adjNexts[i << 1] = adjStarts[node1];
		adjStarts[node1] = i << 1;
		adjNexts[(i << 1) + 1] = adjStarts[node2];
		adjStarts[node2] = (i << 1) + 1;
	}
}
void FindCycle() {
	for(int32_t i = 0; i != n; ++i) {
		if(adjCounts[i] & 1)
			return;
	}

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

		if(adjStarts[node] != -1) {
			int32_t edgeInd = adjStarts[node];
			adjStarts[node] = adjNexts[edgeInd];
			edgeInd >>= 1;

			if(edgeSums[edgeInd] != -1) {
				int32_t next = edgeSums[edgeInd] - node;
				edgeSums[edgeInd] = -1;
				stack[top++] = next;
			}
		} else {
			cycle[cycleLen++] = node;
			--top;
		}
	}
	--cycleLen;
}
void OutputRes(std::ostream& fout) {
	if(cycleLen == m) {
		for(int32_t i = 0; i != cycleLen; ++i)
			fout << (cycle[i] + 1) << ' ';
		fout << '\n';
	} else {
		fout << "-1\n";
	}
}

int main() {
	std::ifstream fin("ciclueuler.in");
	std::ofstream fout("ciclueuler.out");

	ReadGraph(fin);
	FindCycle();
	OutputRes(fout);

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

	return 0;
}