Cod sursa(job #1901607)

Utilizator BonCipBonciocat Ciprian Mircea BonCip Data 4 martie 2017 09:54:44
Problema Ciclu Eulerian Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.3 kb
#include <stdio.h>
#define SPMAX 50

struct pair {
	int x, y;
	bool viz;
};
struct node {
	pair* p;
	node* n;
};
node* all() {
	static int sp = SPMAX;
	static node* st = NULL;
	if (sp == SPMAX) {
		sp = 0;
		st = new node[SPMAX];
	}
	return st + (sp++);
}

namespace Var {
	FILE *fin, *fout;
	int N, M;
	node** G; pair* E;
	int *a, cnt;
}
void dfs(int u) {
	using namespace Var;
	while (G[u] != NULL) {
		if (!G[u]->p->viz) {
			node* curr = G[u];
			G[u] = G[u]->n;
			curr->p->viz = 1;
			dfs(curr->p->x ^ curr->p->y ^ u);
		} else {
			G[u] = G[u]->n;
		}
	}
	a[cnt++] = u;
}
void afis() {
	using namespace Var;
	if (cnt == M + 1 && a[0] == a[M]) {
		for (int i = 0; i < M; ++i) {
			fprintf(fout, "%d ", a[i]);
		}
	} else {
		fprintf(fout, "-1");
	}
	fprintf(fout, "\n");
}

int main()
{
	using namespace Var;
	fin = fopen("ciclueuler.in", "r");
	fout = fopen("ciclueuler.out", "w");
	
	// Citire
	fscanf(fin, "%d%d", &N, &M);
	G = new node*[N + 1]; E = new pair[M];
	for (int i = 0; i < M; ++i) {
		int x, y;
		fscanf(fin, "%d%d", &x, &y);
		E[i].x = x; E[i].y = y; E[i].viz = 0;
		node *fwd = all(), *bwd = all();
		fwd->p = E + i;	bwd->p = E + i;
		fwd->n = G[x];	G[x] = fwd;
		bwd->n = G[y];	G[y] = bwd;
	}
	
	// Procesare
	a = new int[M + 1];
	dfs(E[0].x);
	
	// Afisare
	afis();
	
	fclose(fin);
	fclose(fout);
	return 0;
}