Sicily 1028. Hanoi Tower Sequence

  1. Hanoi Tower Sequence
    Constraints
    Time Limit: 1 secs, Memory Limit: 32 MB
    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
这道题是一个找规律的问题,从题目中所给的样例中我们可以看出
1所在的位置是2的0次方的倍数,但不是2的1次方的倍数
2所在的位置是2的1次方的倍数,但不是2的2次方的倍数
3所在的位置是2的2次方的倍数,但不是2的3次方的倍数
n所在的位置是2的n次方的倍数,但不是2的n-1次方的倍数
所以这道题的核心思想就是把所给的数字不断除以2,每一次除以2都要给结果+1,直到所得数字为奇数
然后这道题还涉及到大整数除法的问题,从高位往低位走,依次除以2,若余数是1的话就把下一位加上10
核心代码如下在这里插入图片描述

#include<iostream>
#include<cstring>
#include<vector>
using namespace std;
int main(){
	int times;
	cin>>times;
	int count=1;
	while(times--){
		if(count!=1){
			cout<<endl;
		}
		string num;
		cin>>num;
		int len=num.size();
		vector<int>v;
		for(int i=0;i<len;i++){
			v.push_back(num[i]-'0');
		}
		int ans=1;
		while(v[len-1]%2!=1){
			for(int i=0;i<len;i++){
				if(v[i]%2!=0){
					v[i+1]+=10;
				}
				v[i]/=2;
			}
			ans++;
		}
		cout<<"Case "<<count++<<": "<<ans<<endl;
	}
} 

猜你喜欢

转载自blog.csdn.net/dcy19991116/article/details/89055164