Strange Tower of Hanoi (recursion)

Weird Tower of Hanoi

Title description The
Tower of Hanoi problem, with the following conditions:

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.

Input format
No input.

Output format
For each integer 1≤n≤12, 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 3 towers. Let a(n) denote the optimal number of steps for n plates and 3 towers. We need to move n-1 plates to the B-pillar first. The optimal number of steps is d(n-1), then move the remaining plate on the A pillar to the C pillar, the number of steps is 1, and finally move the n-1 plates on the B pillar to the C pillar, the optimal number of steps is also Is a(n-1). So there is a recurrence:
a (n) = 2 ∗ a (n − 1) + 1 a(n)=2*a(n-1)+1an=2an1+1
Back to this question, let f(n) denote the optimal number of steps for n plates and 4 towers. Consider moving j plates from A pillar to B pillar. The optimal number of steps is f(j), and then nj Move a plate to the D pillar. Considering that there is already a plate on the B pillar, the optimal number of steps in the 3-tower mode is a(nj). Finally, move j plates to B, the optimal number of steps Also f(j). Consider all j

	for(int i=2;i<=12;i++)
	 a[i]=a[i-1]*2+1;
	for(int i=2;i<=12;i++)
	{
    
    
		f[i]=2147483647;
		for(int j=1;j<=i;j++)
		 f[i]=min(f[i],f[j]*2+a[i-j]);
	}

AC code

#include<cstdio>
#include<algorithm>
using namespace std;
int a[15],f[15];
int main()
{
    
    
	a[1]=1;
	for(int i=2;i<=12;i++)//初值
	 a[i]=a[i-1]*2+1;
	f[1]=1;
	printf("1\n");
	for(int i=2;i<=12;i++)//递推
	{
    
    
		f[i]=2147483647;
		for(int j=1;j<=i;j++)
		 f[i]=min(f[i],f[j]*2+a[i-j]);
		printf("%d\n",f[i]);
	}
 	return 0;
}

Thank you

Guess you like

Origin blog.csdn.net/weixin_45524309/article/details/111400205