这题主要难度就在数据规模比较大,还有就是找规律,他给的数最大能整除2^n,那么就在移动第n+1块板子。
原理:由于汉诺塔的移动是对称的,比如n=3时,1,2,1,3,1,2,1,n=4时,1,2,1,3,1,2,1,4,1,2,1,3,1,2,1。分别他们转成2进制有,
n=3时,001,010,011,100,101,110,111,得出,移动第几块板子和最右边的1在第几位有关系,并且最右的1在第n位,则移动第n块板。
做法:用一个数组来存储大规模的数字,然后大数不断除2,判断什么时候%2为1(即判断最后一位mod 2 = 1),这个时候就说明找到那个在移动的板子。
#include<iostream>
#include<string>
using namespace std;
int div2(int a[],int n)
{
int count = 1;
//找到最右边的1
while(a[n-1] % 2 == 0)
{
count++;
int tmp = 0;
for(int i = 0; i < n; i++)
{
tmp = tmp * 10 + a[i];
a[i] = tmp / 2;
tmp %= 2;
}
}
return count;
}
int main()
{
int n;
cin >> n;
for(int i = 0; i < n; i++)
{
string num;
cin >> num;
int a[num.size()];
for(int j = 0; j < num.size(); j++)
{
a[j] = num[j] - '0';
}
int count = div2(a,num.size());
if(i != 0)
cout << endl << "Case " << i+1 << ": " << count << endl;
else if(i == 0)
cout << "Case " << 1 << ": " << count << endl;
}
}