Strange Towers of Hanoi (Strange Towers of Hanoi)

topic

topic

practice

Yes, it's still practice 1 and practice 2.

Method 1

Violence works miracles! ! ! !

We found that this topic is four towers, so we use quaternary to represent the state of each plate, which is about 2 24 2^{24}22 4 level, use bool array will not explode, then violent simulation can be done.

Wait, it seems that the minimum number of steps is required, then we can use BFS and change bool to int. It's that simple.

BFS opens a queue, just use int inti n t means state, how big is the space?

64MB。。。。。

Yes, this approach is wrong, the space is stuck and cannot be moved, the time is: O (2 24 ∗ 12) O(2^{24}*12)O ( 2241 2 ) , it will also explode, but because each pillar is monotonous, it will be smaller than this in practice, but the space has already exploded, so I won’t try it.

Method 2

Recursion.

Let's think about it, what if the three-pillar Hanluo tower is made.

It is easy to know that for the number of more than two plates, we need at least three pillars to be able to move these plates. When only one plate is moved, only two pillars are needed, so for kkFor k plates, we need to use three pillars to first setk − 1 k-1kMove 1 plate to the second pillar, and then use the two pillars to move thekkk plates to3 33 , thenk − 1 k-1k1 plate uses three pillars to move to thethird 33 roots, to summarize:f (i) = f (i − 1) ∗ 2 + 1 f(i)=f(i-1)*2+1f(i)=f(i1)2+1

So for the four pillars, for kkk plates, due to2 22 or more plates need3 33 pillars, so although we can putii inadvancePut i plates on one column to reduce the moving pressure, but it can only be put on one column at most.

So the recurrence formula comes out: f 4 (n) = f 4 (n − i) + f (i) f_4(n)=f_4(ni)+f(i)f4(n)=f4(ni)+f(i)

#include<cstdio>
#include<cstring>
#include<cstdlib>
#define  N  14
using  namespace  std;
int  f3[N],f4[N];
inline  int  mymin(int  x,int  y){
    
    return  x<y?x:y;}
int  main()
{
    
    
	f3[1]=1;for(int  i=2;i<=12;i++)f3[i]=f3[i-1]*2+1,f4[i]=999999999;
	f4[1]=1;
	for(int  i=2;i<=12;i++)
	{
    
    
		for(int  j=0;j<i;j++)
		{
    
    
			f4[i]=mymin(f4[j]*2+f3[i-j],f4[i]);
		}
	}
	for(int  i=1;i<=12;i++)printf("%d\n",f4[i]);
	return  0;
} 

Guess you like

Origin blog.csdn.net/zhangjianjunab/article/details/107637745