Cod sursa(job #1277664)

Utilizator sunt_emoSunt emo sunt_emo Data 27 noiembrie 2014 23:09:44
Problema Ciclu Eulerian Scor 30
Compilator cpp Status done
Runda Arhiva educationala Marime 1.3 kb
#include <fstream>
#include <vector>

struct Edge
{
  int x, y;
  bool flag, orient;
  Edge(int x, int y): x(x), y(y), flag(false), orient(false) {}
};

int n, m;
std::vector<std::vector<Edge *> > graph;
std::ifstream in("ciclueuler.in");
std::ofstream out("ciclueuler.out");

bool euler(int node, std::vector<Edge *> &sol, int offset=0)
{
  if (offset == (int) sol.size())
	return true;
  Edge *tmp;
  int k;
  bool before;
  for (int i = 0; i < (int) graph[node].size(); i++)
  {
    if (graph[node][i]->flag)
	  continue;
	tmp = graph[node][i];
	tmp->flag = true;
	sol[offset] = tmp;
	before = tmp->orient;
	if (tmp->x == node)
	  k = tmp->y;
	else
	  tmp->orient = !tmp->orient, k = tmp->x;
	if (euler(k, sol, offset + 1))
	  return true;
	tmp->flag = false, tmp->orient = before;
  }
  return false;
}

int main()
{
  in >> n >> m;
  
  graph = std::vector<std::vector<Edge *> >(n + 1);
  
  for (int i = 0; i < m; i++)
  {
    int u, v;
	in >> u >> v;
	Edge *e = new Edge(u, v);
	graph[u].push_back(e);
	if (v != u)
	  graph[v].push_back(e);
  }
  
  std::vector<Edge *> sol(m);
  int start_node = 1;
  euler(start_node, sol);
  
  for (int i = 0; i < m; i++)
    if (!sol[i]->orient)
	  out << sol[i]->x << ' ';
	else
	  out << sol[i]->y << ' ';
  out << '\n';
}