Tower of Hanoi

Title

An extra plate is added to the traditional Tower of Hanoi game.
How many steps does it take to move the n-story Tower of Hanoi from the first plate to the fourth plate?

Ideas

Relive the classic Tower of Hanoi

To move layer n from disk 1 to disk 3, it needs to be divided into three steps:
1: Move layer n-1 from No. 1 to No. 2 (layer n must be moved to No. 3, in order not to affect the movement of layer n Can only be moved to No. 2)
2: Move layer n from 1 to No.
3: 3: Move layer n-1 from No. 2 to No. 3

The first step can be subdivided into three similar steps

Until the total number of layers currently moved is 1, only one step is required, recursion.

Therefore, in the classic Tower of Hanoi game, the minimum number of steps for the n-layer is
d[n] = d[n-1] + 1 + d[n-1]
d[1] = 1

Tower of Hanoi

The classic Tower of Hanoi has three trays. In one movement, only two trays can be used for operation except the starting tray. Therefore
, the answer of the classic n-layer Nobetta can be understood as:
In the case of two vacancies , The number of steps required to move an n-story tower is d[n].

Then in the four-play Tower of Hanoi game, there can be three free disks for operation.
When you need to move the n-layer Hanoi Tower, you can move the upper i-layer to an empty disk, leaving two empty disks.
Move the ni layer in the remaining two empty disks, which is obviously d[n-1].
Therefore, the minimum number of moving steps for the n layer is
f[n] = f[i] + d[ni] + f [i]
f[1] = 1

ac source code

#include<bits/stdc++.h>
using namespace std;
#define ull unsigned long long
const int maxn = 15;

int d[maxn];
int f[maxn];

int main(){
    
    
	d[1] = 1;
	for(int i = 2 ; i <= 12 ; i++){
    
    
		d[i] = d[i-1]*2 + 1;
		f[i] = 1000000000;
	}

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

	for(int i = 1 ; i <= 12 ; i++)cout << f[i] << endl;

}

Guess you like

Origin blog.csdn.net/qq_35068676/article/details/108902485