Cod sursa(job #3224552)

Utilizator vladdobro07vladdd vladdobro07 Data 15 aprilie 2024 16:59:18
Problema Ciclu Eulerian Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <bits/stdc++.h>

using namespace std;

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

const int nmax = 1e5, mmax = 5e5;

struct muchie {
	int nextnod, index;
};

vector<muchie> g[nmax + 1];
vector<int> ans(mmax + 1);
vector<bool> a(mmax + 1);

int n, m, x, y, len = 0;

void read() {
	fin >> n >> m;
	for(int i = 1; i <= m; i++) {
		fin >> x >> y;
		g[x].push_back({y, i});
		g[y].push_back({x, i});
	}
}

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

void dfs(int nod) {
	stack<int> stk;
	stk.push(nod);
	while(!stk.empty()) {
		nod = stk.top();
		if(g[nod].size() == 0) {
			ans[++len] = nod;
			stk.pop();
		} else if(a[g[nod].back().index] == 1) {
			g[nod].pop_back();
		} else {
			a[g[nod].back().index] = 1;
			stk.push(g[nod].back().nextnod);
		}
	}
}

void euler() {
	dfs(1);
	for(int i = 1; i <= m; i++)
		fout << ans[i] << " ";
}

int main() {
	read();
	if(can_euler())
		euler();
	else
		fout << -1;
	return 0;
}