问题 E: Little Sub and Traveling
时间限制: 1 Sec 内存限制: 256 MB
提交: 97 解决: 31
[提交] [状态] [命题人:admin]
题目描述
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
(题意:给你一个n,表示有n个点,编号为0~n-1。从点i可以走到(2*i)%n和(2*i+1)%n。让你找出一条从0开始经过其他点,再回到0的回路。)
(思路:
1.当n为奇数时,假设n=2*k+1,那么最后回到0时,肯定是从k走回去的;而对于2*k(即n-1)也一定是从k走过去的,所以,答案不存在。
2.当n为偶数时,可以发现i和i+n/2走到的两个点是一样的,我们可以把i和i+n/2看作一个点,对于每个这样的点都有两条入边和出边,即点的入度和出度相同。显然,我们就将问题转化为了求解欧拉回路的问题。对于要求的字典序最大,求欧拉回路时,优先走大的点就可以了。
)
(https://blog.csdn.net/PacosonSWJTU/article/details/50007847)
#include <bits/stdc++.h>
using namespace std;
const int N = 1e4+10;
int vis[N],ans[N],cnt,n;
void dfs(int x)
{
if(!vis[(2*x+1)%n])
{
vis[(2*x+1)%n]=1;
dfs((2*x+1)%(n/2));
ans[cnt++]=(2*x+1)%n;
}
if(!vis[(2*x)%n])
{
vis[(2*x)%n]=1;
dfs((2*x)%(n/2));
ans[cnt++]=(2*x)%n;
}
return ;
}
int main(void)
{
cnt=0;
scanf("%d",&n);
if(n&1)
{
printf("-1\n");
return 0;
}
for(int i=0;i<n;i++)
vis[i]=0;
ans[cnt++]=0;
vis[0]=1;
dfs(0);
ans[cnt++]=0;
for(int i=cnt-1;i>=0;i--)
printf("%d%c",ans[i],i==0?'\n':' ');
return 0;
}