Cod sursa(job #260867)

Utilizator scvalexAlexandru Scvortov scvalex Data 17 februarie 2009 17:29:58
Problema Ciclu Eulerian Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <cstdio>
#include <vector>

using namespace std;

int N;
int U[500010], V[500010];
vector<int> G[100001];
int kk[100001];
int S[500010], L;
bool used[500010];
int R[500010], Rn;

bool este_eulerian() {
	int i;
	for (i = 1; i <= N; ++i)
		if (!G[i].size() || (G[i].size() % 2 == 1)) {
			return false;
		}
	return true;
}

int main(int argc, char *argv[]) {
	int i, M, n;

	FILE *fi = fopen("ciclueuler.in", "r");
	fscanf(fi, "%d %d", &N, &M);
	for (i = 1; i <= M; ++i) {
		fscanf(fi, "%d %d", U+i, V+i);
		G[U[i]].push_back(i);
		G[V[i]].push_back(i);
	}
	fclose(fi);

	FILE *fo = fopen("ciclueuler.out", "w");
	if (!este_eulerian()) {
		fprintf(fo, "-1\n");
		fclose(fo);
		return 0;
	}

	L = 1;
	S[L] = 1;

	while (L > 0) {
		n = S[L];
		for (; (kk[n] < (int)G[n].size()) && used[G[n][kk[n]]]; ++kk[n])
			;

		if (kk[n] < (int)G[n].size()) {
			used[G[n][kk[n]]] = true;
			if (n == U[G[n][kk[n]]])
				S[++L] = V[G[n][kk[n]]];
			else
				S[++L] = U[G[n][kk[n]]];
			++kk[n];
		} else {
			R[++Rn] = S[L--];
		}
	}

	if (Rn < M) {
		fprintf(fo, "-1\n");
		fclose(fo);
		return 0;
	}

	for (i = 1; i < Rn; ++i)
		fprintf(fo, "%d ", R[i]);
	fprintf(fo, "\n");
	fclose(fo);

	return 0;
}