1028. Hanoi Tower Sequence
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.
Given an integer p, your task is to find out the pth element of this sequence.
Input
The first line of the input file is T, the number of test cases.
Each test case contains one integer p (1<=p<10^100).
Output
Output the pth element of the sequence in a single line. See the sample for the output format.
Print a blank line between the test cases.
Sample Input
4 1 4 100 100000000000000
Sample Output
Case 1: 1 Case 2: 3 Case 3: 3 Case 4: 15
Problem Source
ZSUACM Team Member
思路:这个,刚刚觉得就应该要找点关系,后来,找出的比较弱智,二进制,最右边的1所在的位数。
代码:
#include <iostream>
#include <string>
using namespace std;
int div2Times(string num)
{
int sum = 1;
if ((num[num.size() - 1] - '0') % 2)
{
return sum;
}
int length = num.size() - 1;
int i;
while ( true)
{
for(i = 0; i < length; i++)
{
if ((num[i] - '0') % 2)
{
num[i] -= 1;
num[i + 1] += 10;
}
num[i] = num[i] - (num[i] - '0') / 2;
}
if ((num[i] - '0') % 2)
{
return sum;
}
else
{
num[i] = num[i] - (num[i] - '0') / 2;
sum++;
}
}
return sum;
}
int main()
{
string number;
int n;
cin >> n;
cin >> number;
cout << "Case " << 1 << ": " << div2Times(number) << endl;
for (int i = 1; i < n; i++)
{
cin >> number;
cout << endl << "Case " << i+ 1 << ": " << div2Times(number) << endl;
}
return 0;
}