Cod sursa(job #2820188)

Utilizator izotova_dIzotova Daria izotova_d Data 19 decembrie 2021 23:46:39
Problema Ciclu Eulerian Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.03 kb
#include <iostream>
#include <vector>
#include <stack>
#include <fstream>

using namespace std;

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

class Graph
{
private:
	//number of nodes
	int n;
	//number of edges
	int e;
	bool oriented = true;
	//adj list for graph representation
	vector<vector<int>> adj_list;
public:
	Graph() {}
	virtual ~Graph() {}

	vector<int> euler_cycle()
	{
		fin >> this->n;
		
		//created adj list with all the edges being indexed
		vector<pair<int, int>> empty;
		vector<vector<pair<int, int>>> adj_list_indexed(this->n,empty);

		fin >> this->e;
		for (int i = 0; i < this->e; i++)
		{
			int n1, n2;
			fin >> n1;
			n1--;
			fin >> n2;
			n2--;

			adj_list_indexed[n1].push_back(make_pair(n2, i));
			adj_list_indexed[n2].push_back(make_pair(n1, i));
			
		}

		for (int i = 0; i < adj_list_indexed.size(); i++)
		{
			if (adj_list_indexed[i].size() % 2 != 0)
			{
				vector<int> res;
				res.push_back(-1);
				res.push_back(-1);
				return res;
			}
		}

		//bool vector to see if edge was already removed
		vector<bool> edge_removed(this->e, false);

		//create stack to remember the path
		stack<int> path;
		//for cycle we can start from any node, so let's start with 0
		path.push(0);

		while (!path.empty())
		{
			int current_node = path.top();

			if (!adj_list_indexed[current_node].empty())
			{
				pair<int, int> next_node_index = adj_list_indexed[current_node].back();
				adj_list_indexed[current_node].pop_back();

				if (!edge_removed[next_node_index.second])
				{
					edge_removed[next_node_index.second] = true;
					path.push(next_node_index.first);
				}
			}
			else
			{
				vector<int> res;
				while (path.size() > 1)
				{
					res.push_back(path.top()+1);
					path.pop();
				}
				return res;
			}
		}

	}
	
};

int main()
{
	Graph graph;
	vector<int> result = graph.euler_cycle();
	for (int i = 0; i < result.size(); i++)
	{
		fout << result[i] << " ";
	}
	
	fout.close();
	return 0;
}