问题 E: Little Sub and Traveling

题目描述

Little Sub lives in a country with n cities A[0..n-1]. He loves traveling very much.
It is Feb.14th, the Valentine Day. Little Sub decides to travel around the country with his girl friend.
Little Sub lives in A[0] and he wants to visit each city exactly once and go back to A[0] eventually.
However, Little Sub has made a rule for his journey: Suppose he is in city A[i], the next city he is about to visit must be either A[(i*2)%n] or A[(i*2 + 1)%n].
Please help him fi nd a possible route. If there are multiple answers, please give the one with the maximum alphabet order.
We say route A is larger than route B in the alphabet order when there exists i that A[i] > B[i]&A[1..i-1] = B[1..i-1] meets.

 

输入

The first line contains a positive integers n(2≤n≤10000).

 

输出

If there exists a legal route, please output n+1 integer separated by spaces in a single line, indicating the route.
If there is no possible route, please output  -1 instead.

 

样例输入

4

样例输出

0 1 3 2 0

 

打表发现奇数无解,偶数有解。

并且偶数的时候 可知  xx+n/2  所得的结果是一样的, 所以将 其看做一个节点, 每个节点,入度为2,出度为2,所以必定存在欧拉回路(套圈法), 贪心每次找最大的即可。

 

#include<bits/stdc++.h>
using namespace std;

typedef long long LL;
#define rep(i,a,b) for(int i=a;i<b;++i)

int fd;

stack<int> stk;
int vis[10010];

void dfs(int now,int x,int n)
{
	if(now==n) {
		return;
	}

	int a=(x*2)%n;
	int b=(x*2+1)%n;
	int mx=max(a,b),mi=min(a,b);

//	printf("x:%d mx:%d mi:%d\n",x,mx,mi);
	
	if(!vis[mx]) {
		vis[mx]=1;
		
		dfs(now+1,mx,n);
		
		stk.push(mx);
	}
	
	if(!vis[mi]) {
		vis[mi]=1;
		dfs(now+1,mi,n);
	 	stk.push(mi);
	}
}

int main()
{
//	freopen("out2.txt","w",stdout);
	int n;
	while(scanf("%d",&n)==1) {
		memset(vis,0,sizeof(vis));
			
		if(n&1)printf("-1\n");
		else {
			fd=0;
			
			vis[0]=1;
			stk.push(0);
			dfs(1,0,n);
		
		//	printf("fd:%d\n",fd);
			int m=stk.size();
			
			//printf("m:%d\n",m);
			printf("0 ");
			rep(i,0,m){
				int x=stk.top();
				stk.pop();
				printf("%d%c",x,i==m-1?'\n':' ');
			}
		}
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值