SOJ 1028. Hanoi Tower Sequence

这题主要难度就在数据规模比较大,还有就是找规律,他给的数最大能整除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;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值