[Ybtoj Chapter 1 Example 2] Hanoi Tower Problem [Recursion]

Title description

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 the tower. Please find out the minimum number of movements required to move all the discs from Tower A to Tower D.


Input format
No input.

Output format
For each integer n (1 <= n <= 12 n(1<=n<=12n1<=n<=1 2 , output a minimum number of moves that meet the condition, and each result occupies one line.


Problem solving ideas

First consider the Tower of Hanoi problem with three towers, we set d(n) d(n)d ( n ) represents the optimal number of steps for n plates and 3 towers, we need to first setn − 1 n-1n1 plate is moved to the B-pillar, the optimal number of steps isd (n − 1) d (n-1)dn1 ) , and then move the remaining plate on the A pillar to the C pillar, the number of steps is 1, and finally then − 1 n-1on the B pillarn1 plate is moved to the C pillar, the optimal number of steps is alsod (n − 1) d (n-1)dn1 ) . Inherent recurrence:d (n) = 2 ∗ d (n − 1) + 1 d(n)=2*d(n-1)+1d(n)=2d(n1)+1

Back to this question, let f(n) f(n)f ( n ) represents the optimal number of steps for n plates and 4 towers, consider movingjfrom the A column(0 <= j <= n) j (0<=j<=n)j0<=j<=n ) plates onto the B-pillar, the optimal number of steps isf(j) f(j)f ( j ) . And thenn − j njnMove the j plates to the D column. Considering that the size of the disk on the B column is small and the plate cannot be placed, it becomes a three-tower mode. The optimal number of steps isd (n − j) d (nj)dnj ) , and finally move j plates to the D column, the optimal number of steps isf(j) f(j)f ( j ) . Considering all j, the inherent recurrence:f (n) = min (2 ∗ f (j) + d (n − j), f (n) f(n)=min{(2*f(j)+ d(nj),f(n)}fn=m i n ( 2f(j)+d(nj),f(n)


Code

#include<iostream>
#include<cstdio>
using namespace std;
const int INF=2147483600;
int d[20],f[20];
int main(){
    
    
	d[1]=1;
	for(int i=2;i<=12;i++)
	 	d[i]=d[i-1]*2+1;
	f[1]=1;
	printf("%d\n",f[1]);
	for(int i=2;i<=12;i++)
	{
    
    
		f[i]=INF;
		for(int j=1;j<=i;j++)
			f[i]=min(f[i],2*f[j]+d[i-j]);
		printf("%d\n",f[i]);
	}
}

Guess you like

Origin blog.csdn.net/kejin2019/article/details/111598352