题目描述
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
打表发现奇数无解,偶数有解。
并且偶数的时候 可知 和 所得的结果是一样的, 所以将 其看做一个节点, 每个节点,入度为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;
}