Cod sursa(job #3149819)

Utilizator daristyleBejan Darius-Ramon daristyle Data 12 septembrie 2023 21:06:34
Problema Ciclu Eulerian Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <fstream>
#include <vector>

using namespace std;

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

const int NODES_MAX = 1e5;
vector<int> edge[NODES_MAX];
vector<int> cycle;
bool marked[NODES_MAX];

inline void addEdge(int u, int v){
	edge[u].push_back(v);
	edge[v].push_back(u);
}

inline bool hasNeighbours(const int& node){
	return !edge[node].empty();
}

inline int ChooseANeighbourAndErase(const int& node){
	int neighbour = edge[node].back();
	edge[node].pop_back();
	int i = 0;
	while(edge[neighbour][i] != node)
		++i;
	swap(edge[neighbour][i], edge[neighbour].back());
	edge[neighbour].pop_back();
	return neighbour;
}

void euler(const int& node){
	while(hasNeighbours(node)){
		int neighbour = ChooseANeighbourAndErase(node);
		euler(neighbour);
	}

	cycle.push_back(node);
}

int dfs(int node){
	int retval = 1;
	marked[node] = true;
	for(auto neighbour: edge[node])
		if(!marked[neighbour])
			retval += dfs(neighbour);

	return retval;
}

inline bool isConex(int nodes){
	return dfs(0) == nodes;
}

inline bool isEulerian(int nodes){
	int odds = 0;
	for(int node = 0; node < nodes; ++node)
		odds += edge[node].size() & 1;

	return !odds && isConex(nodes);
}

int main(){
	int nodes, edges, u, v;
	fin >> nodes >> edges;
	for(int i = 0; i < edges; ++i){
		fin >> u >> v;

		addEdge(u - 1, v - 1);
	}

	if(isEulerian(nodes)){
		u = 0;
		euler(u);
		cycle.pop_back();

		for(auto x: cycle)
			fout << x + 1 << ' ';
		fout.put('\n');
	}else
		fout << "-1\n";

	fin.close();
	fout.close();
	return 0;
}