Cod sursa(job #2817997)

Utilizator Octavian21Chiriac Octavian Octavian21 Data 14 decembrie 2021 22:52:07
Problema Ciclu Eulerian Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.29 kb
#include<iostream>
#include<fstream>
#include<vector>

using namespace std;

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

class Graf {

	int n;
	int m;
	vector<vector<int>> adj;

public:


	Graf(int n, int m, vector<vector<int>> adj)
	{
		this->n = n;
		this->m = m;
		this->adj = adj;
	}


	void addEdge(int x, int y)
	{
		adj[x].push_back(y);
		adj[y].push_back(x);
	}

	void removeEdge(int x, int y) {

		for (int i = 0; i < adj[y].size(); ++i)
		{
			if (adj[y][i] == x)
			{
				swap(adj[y][i], adj[y][adj[y].size() - 1]);
				adj[y].pop_back();
				break;
			}
		}


		for (int i = 0; i < adj[x].size(); ++i)
		{
			if (adj[x][i] == y)
			{
				swap(adj[x][i], adj[x][adj[x].size() - 1]);
				adj[x].pop_back();
				break;
			}
		}

	}

	void print()
	{

		int odd = 0;

		for (int i = 1; i <= n; ++i)
		{
			if (adj[i].size() % 2 == 1)
			{
				odd++;
			}

		}
		if (odd == 0)
		{
			printEuler(1);
		}
		else
		{
			out << -1;
		}

	}

	void printEuler(int nodp)
	{


		//out<<nodp<<" ";


		if (adj[nodp].size() == 0)
		{
			return;
		}
		else
			out << nodp << " ";


		if (adj[nodp].size() == 1)
		{
			int nodc = adj[nodp][0];
			removeEdge(nodp, nodc);
			printEuler(nodc);
			return;
		}


		for (auto nodc : adj[nodp])
		{
			if (nuPod(nodp, nodc))
			{
				removeEdge(nodp, nodc);
				printEuler(nodc);
				return;
			}

		}

	}

	bool nuPod(int nodp, int nodc)
	{
		int c1 = 0, c2 = 0;
		vector<bool> visited;

		removeEdge(nodp, nodc);
		visited = vector<bool>(n + 1, false);
		c1 = nrNod(nodc, visited);

		addEdge(nodp, nodc);
		visited = vector<bool>(n + 1, false);
		c2 = nrNod(nodc, visited);


		if (c2 == c1)
			return true;
		else
			return false;

	}


	int nrNod(int nodp, vector<bool>& visited)
	{
		visited[nodp] = true;
		int count = 1;
		for (auto nodc : adj[nodp])
		{
			if (visited[nodc] == false)
			{
				count += nrNod(nodc, visited);
			}
		}
		return count;

	}

};

int main()
{
	int n, m, x, y;
	in >> n >> m;
	vector<vector<int>> adj(n + 1);

	for (int i = 1; i <= m; ++i)
	{
		in >> x >> y;
		adj[x].push_back(y);
		adj[y].push_back(x);
	}
	Graf g(n, m, adj);

	g.print();

	return 0;
}