[Ybtoj High-efficiency Advanced 1.1] [Recursion] The strange Tower of Hanoi

[Ybtoj High-efficiency Advanced 1.1] [Recursion] The strange Tower of Hanoi

topic

Insert picture description here


Problem-solving ideas

First consider that there are only 3 towers
. The optimal number of steps to move i is m[i].
If there are a total of n rings to be moved

  • Move n-1 rings to Tower B first, then m[n-1] steps are required
  • Then put the nth ring on the C tower, it takes 1 step
  • Finally, put these n-1 towers into tower C, which requires m[n-1] steps

From this, the law of 3 towers is obtained:
m[i]=2*m[i-1]+1

Then consider the problem
. The optimal number of steps for the 4 towers to move i is f[i].
There is no way to know the state of the first n-1 rings.

  • You can first consider putting j to Tower B, which requires f[j] steps
  • The remaining nj is the 3-tower problem, which requires m[nj] steps
  • Finally, put these j into the C tower, which requires f[j] steps

Thus, the law of 4 towers is obtained:
f[i]=min(f[i],2*f[j]+d[nj]) (1<=j<=i)


Code

#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
long long m[20],f[20];
int main()
{
    
    
    memset(f,0x7f,sizeof(f));
	m[1]=f[1]=1;
	for (int i=2;i<=12;i++)
	     m[i]=2*m[i-1]+1;  //预处理3塔 
	for (int i=2;i<=12;i++)  //枚举环数 
        for (int j=1;j<=i;j++)  //枚举先移去B塔的环数 
            f[i]=min(f[i],2*f[j]+m[i-j]);
    for (int i=1;i<=12;i++)
        printf("%lld\n",f[i]);
    return 0;
} 

Guess you like

Origin blog.csdn.net/qq_45621109/article/details/111636168