Description
Hanoi Tower is a famous game invented by the French mathematician Edourard Lucas in 1883. We are given a tower of n disks, initially stacked in decreasing size on one of three pegs. The objective is to transfer the entire tower to one of the other pegs, moving only one disk at a time and never moving a larger one onto a smaller. The best way to tackle this problem is well known: We first transfer the n-1 smallest to a different peg (by recursion), then move the largest, and finally transfer the n-1 smallest back onto the largest. For example, Fig 1 shows the steps of moving 3 disks from peg 1 to peg 3. Now we can get a sequence which consists of the red numbers of Fig 1: 1, 2, 1, 3, 1, 2, 1. The ith element of the sequence means the label of the disk that is moved in the ith step. When n = 4, we get a longer sequence: 1, 2, 1, 3, 1, 2, 1, 4, 1, 2, 1, 3, 1, 2, 1. Obviously, the larger n is, the longer this sequence will be.
Input
The first line of the input file is T, the number of test cases.
Output
Output the pth element of the sequence in a single line. See the sample for the output format.
Sample Input
4 1 4 100 100000000000000
Sample Output
Case 1: 1 Case 2: 3 Case 3: 3 Case 4: 15 |
1028. Hanoi Tower Sequence
| |||||||||
| |||||||||
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=600;
int t[maxn],A[maxn];
//{ 0-9,A-Z,a-z } 62中符号
void change(int a,int b,char *s,char *d)//s在a进制下,转换成b进制,保存到d中
{
int i,k,l;
for(k=i=strlen(s);0<i--;)
t[k-1-i]=s[i]-(s[i]<58?48:s[i]<97?55:61);
for(l=0;k;)
{
for(i=k;1<i--;)
{
t[i-1]+=t[i]%b*a;
t[i]/=b;
}
A[l++]=t[0]%b;
t[0]/=b;
for(;0<k&&!t[k-1];k--);
}
for(d[l]=i=0;i<l;i++)
d[l-1-i]=A[i]+(A[i]<10?48:A[i]<36?55:61);
}
int main()
{
int ci;scanf("%d",&ci);
for(int pl=1;pl<=ci;pl++)
{
if(pl>1) printf("/n");
char a[maxn],b[maxn];
scanf("%s",a);
change(10,2,a,b);
int cnt=1;
for(int i=strlen(b)-1;i>=0&&b[i]=='0';i--) cnt++;
printf("Case %d: %d/n",pl,cnt);
}
return 0;
}