Preliminary study and comprehension of the Tower of Hanoi note example HDU1995

The Tower of Hanoi comes from a story in Indian legend. When God created the world, he made three diamond pillars, and on one pillar were stacked 64 golden discs in order from bottom to top . God instructed the Brahmins to rearrange the disc on another pillar . And it is stipulated that the disk cannot be enlarged on the small disk, and only one disk can be moved at a time between the three pillars.

When there is only one plate, just move one plate from Tower A to Tower C.

When there are two plates on tower A, first move the No. 1 plate (numbered from top to bottom) on the A tower to the B tower, then move the No. 2 plate on the A tower to the C tower, and finally move the B The small plate on the tower moves to the C tower.

When there are 3 disks on Tower A, first move the disks numbered 1 to 2 (2 total) on Tower A to Tower B (with the help of Tower C), and then move the largest disk number 3 on Tower A Go to Tower C, and finally move the two plates on Tower B to Tower C with the help of Tower A.

When there are n plates on the A tower, first move the plates numbered 1 to n-1 on the A tower (n-1 in total) to the B tower (with the help of the C tower), and then move the largest n number on the A tower. The plate is moved to the C tower, and finally n-1 plates on the B tower are moved to the C tower with the help of the A tower.

To sum up, except that when there is only one plate, there is no need to use other towers, the rest of the situation is the same (only the complexity of the event is different), and the number of moves of plate k is only related to the number of plates under k, and is related to the number of plates under k. The number of plates above k is irrelevant .

k==1, move 1 time;
  k==2, 1 moves 2 times, 2 moves 1 time;
  k==3, 1 moves 4 times; 2 moves 2 times; 3 moves 1 time;
 From this, we guess that plate i moves twice as many times as plate i-1 during the move
#include <iostream>
#include <cstdio>
using namespace std;

intmain()
{
    int t;
    cin>>t;
    int n,k;
    __int64 num;
    while(~scanf("%d%d",&n,&k)){
        num=1;
        for(int i=1;i<=n-k;i++){
            num*=2;
        }
        cout<<num<<endl;
    }
    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325894661&siteId=291194637