Pagini recente » Cod sursa (job #203374) | Cod sursa (job #1560890) | Cod sursa (job #2080630) | Cod sursa (job #596114) | Cod sursa (job #2820185)
#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));
}
//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] << " ";
}
return 0;
}