Ouroboros Snake
Description
Ouroboros is a mythical snake from ancient Egypt. It has its tail in its mouth and continously devours itself.
The Ouroboros numbers are binary numbers of 2^n bits that have the property of "generating" the whole set of numbers from 0 to 2^n - 1. The generation works as follows: given an Ouroboros number, we place its 2^n bits wrapped in a circle. Then, we can take 2^n groups of n bits starting each time with the next bit in the circle. Such circles are called Ouroboros circles for the number n. We will work only with the smallest Ouroboros number for each n. Example: for n = 2, there are only four Ouroboros numbers. These are 0011;0110;1100; and 1001. In this case, the smallest one is 0011. Here is the Ouroboros circle for 0011: The table describes the function o(n;k) which calculates the k-th number in the Ouroboros circle of the smallest Ouroboros number of size n. This function is what your program should compute. Input
The input consists of several test cases. For each test case, there will be a line containing two integers n and k (1<=n<=15; 0<=k<2^n). The end of the input file is indicated by a line containing two zeros. Don抰 process that line.
Output
For each test case, output o(n;k) on a line by itself.
Sample Input 2 0 2 1 2 2 2 3 0 0 Sample Output 0 1 3 2 Source |
还是经典的欧拉回路。
#include <stdio.h>
#include<string.h>
int v[1<<15|1],ma,mi,ans,cnt,k;
//v标记是否访问过。ma和mi分别记录k字节可构成数的上界和高位。
void dfs(int u)
{
if(cnt==ma-k)//如果找到了第k个直接返回
return;
int i,t;
for(i=0;i<2;i++)
{
t=((u%mi)<<1)+i;
if(!v[t]&&t<ma)
{
v[t]=1;
dfs(t);
cnt++;
if(cnt==ma-k)//记录答案
{
ans=t;
return;
}
}
}
}
int main()
{
int n;
while(scanf("%d%d",&n,&k),n||k)
{
memset(v,0,sizeof v);
cnt=0;
mi=1<<(n-1);
ma=mi<<1;
dfs(0);
printf("%d\n",ans);
}
return 0;
}