题意:
给出汉诺塔原型
求在第几步的时候这个汉诺塔每一根柱子上面的盘子数一样多
题解:
打表找规律
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
int k;
int s[10];
int hanoi(char a,char b,char c,int n)
{
if(n==0)
return 0;
if(hanoi(a,c,b,n-1))
return 1;
--s[a-'a'],++s[b-'a'],s[c-'a'];
if(s[a-'a']==s[b-'a']&&s[b-'a']==s[c-'a']){
printf("%d\n",k);
return 1;
}
k++;
if(hanoi(c,b,a,n-1))
return 1;
}
int main()
{
int n;
//freopen("out.txt","w",stdout);
for(int i=3;i<=30;i+=3)
{
k=1;
s[0]=i;
s[1]=s[2]=0;
hanoi('a','b','c',i);
}
return 0;
}
得到规律:
num【3】= 2,num【6】=9,num【12】=38
当 i 为奇数的时候:num【i】=num【i-3】*4+2
当 i 为偶数的时候:num【i】=num【i-3】*4 - t【i】
其中 t【i】=t【i-6】*4+21
然后大整数处理一下就可以了
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException {
Scanner cin = new Scanner(new File("input.txt"));
PrintWriter print = new PrintWriter(new File("output.txt"));
int n;
BigInteger []t = new BigInteger[307];
BigInteger []num = new BigInteger[307];
num[3] = BigInteger.valueOf(2);
num[6] = BigInteger.valueOf(9);
t[12] = BigInteger.valueOf(17);
num[9] = BigInteger.valueOf(38);
for(int i = 12;i<=300;i+=3){
if((i%2)==0){
num[i] = num[i-3].multiply(BigInteger.valueOf(4)).subtract(t[i]);
t[i+6] = t[i].multiply(BigInteger.valueOf(4)).add(BigInteger.valueOf(21));
}else {
num[i] = num[i-3].multiply(BigInteger.valueOf(4)).add(BigInteger.valueOf(2));
}
}
while(cin.hasNext()){
n = cin.nextInt();
print.println(num[n]);
}
cin.close();
print.close();
}
}