[Ybt] [Basic calculation recurrence class example 2] Strange Tower of Hanoi

Weird Tower of Hanoi

Topic link: Strange Tower of Hanoi


Topic

The conditions of the Tower of Hanoi are as follows:

  • There are four towers A, B, C and D.
  • Here is a disc, the number of is constant.
  • The size of each disc is different.
  • All the discs are stacked on tower A at the beginning, and the size of the discs gradually increases from the top of the tower to the bottom of the tower.
  • We need to transfer all the discs from Tower A to Tower D.
  • One disc can be moved at a time. When the tower is empty or the size of the top disc is larger than the moved disc, the disc can be moved to this tower.

Please find out the minimum number of movements required to move all the discs from Tower A to Tower D

Problem solving ideas

Obviously, this is a problem of the Tower of Hanoi with four towers .

First we consider the problem of the Tower of Hanoi with three towers .

It is well known that the three towers are set d (n) d(n)d ( n ) isnnThe optimal solution of n plates,AAA isn - 1 n-1n1 plate placed onBBB , the optimal number of steps isd (n − 1) d(n-1)d(n1 ) ; then the remaining1 11 plate toCCC and finallyBBN − 1 n-1on Bn1 plate toCCC , the optimal number of steps is alsod (n − 1) d(n-1)d(n1 ) , so there is a recurrenced (n) = 2 ∗ d (n − 1) + 1 d(n)=2*d(n-1)+1d(n)=2d(n1)+1

Now let us consider the problem of the Tower of Hanoi with four towers .

We also set f (n) f(n)f ( n ) meansnnThe optimal solution of the four-tower tower of Hanoi with n discs.
We putBBB is regarded as a transit, andjjj disks moved toBBOn B , the optimal number of steps isf (j) f(j)f ( j ) .
Then there isn − j njleftnj plates due toBBThere is already a plate on B , the remainingAAA C C C D D D constitutes atowerofHanoiproblem withthree towers, and the optimal number of steps isd (n − j) d(nj)d(nj ) .
FinallyBBJjon Bmove j plates toDDOn D , the optimal number of steps is alsof (j) f(j)f(j)
则递推式为:
f ( n ) = m i n { 2 ∗ f ( j ) + d ( n − j ) }                    0 ≤ 1 ≤ n \begin{array}{l}f(n)=min\{2\ast f\left(j\right)+d\left(n-j\right)\}\\\;\;\;\;\;\;\;\;\;0\leq1\leq n\end{array} f(n)=m i n { 2f(j)+d(nj)}01n
We finally enumerate jjj , takeminfor the answer⁡ \minmin is fine.

code

#include<iostream>
#include<cstdio>
using namespace std;

int d[20];
int f[20];

int main()
{
    
    
	for(int i=1;i<=12;i++)
		d[i]=2*d[i-1]+1;
	f[1]=1;
	cout<<1<<endl;
	for(int i=2;i<=12;i++)
	{
    
    
		f[i]=0x3f3f3f3f;
		for(int j=1;j<=i;j++)
			f[i]=min(f[i],2*f[j]+d[i-j]);
		cout<<f[i]<<endl;
	}
}

Guess you like

Origin blog.csdn.net/SSL_guyixin/article/details/111633596