Hackerrank :Gena Playing Hanoi

来源:互联网 发布:js 字符串函数大全 编辑:程序博客网 时间:2024/05/16 19:53

Gena Playing Hanoi

locked
by nikasvanidze

The Tower of Hanoi is a famous game consisting of 33 rods and a number of discs of incrementally different diameters. The puzzle starts with the discs neatly stacked on one rod, ordered by ascending size with the smallest disc at the top. The game's objective is to move the entire stack to another rod, obeying the following rules:

  1. Only one disc can be moved at a time.
  2. Each move consists of taking the topmost disc from a stack and moving it to the top of another stack.
  3. No disc may be placed on top of a smaller disc.

Gena has a modified version of the Tower of Hanoi. His Hanoi has 44 rods and NN discs ordered by ascending size. He made a few moves (following the rules above), but stopped and lost his place. He wants to restore the tower to its original state by making valid moves. Given the state of Gena's Hanoi, help him calculate the minimum number of moves needed to restore the tower to its original state.

Note: Gena's rods are numbered from 11 to 44. All discs are initially located on rod 11.

Input Format

The first line contains a single integer, NN, denoting the number of discs. 
The second line contains NN space-separated integers, where the ithith integer is the index of the rod where the disk with diameter ii is located.

Constraints

  • 1N101≤N≤10

Output Format

Print the minimum number of moves Gena must make to restore the tower to its initial, ordered state on the first rod.

Sample Input

31 4 1

Sample Output

3

Explanation

33 moves are enough to build the tower. Here is one possible solution: 


这个题做法是深搜,没想到。最多10个盘子,4个塔,于是一个整数20位就可以表示当前状态,枚举移动的过程。

代码:

#pragma warning(disable:4996)#include <iostream>#include <functional>#include <algorithm>#include <cstring>#include <vector>#include <string>#include <cstdio>#include <cmath>#include <queue>#include <stack>#include <deque>#include <set>#include <map>using namespace std;typedef long long ll;#define INF 0x3fffffff#define repp(i, n, m) for (int i = n; i <= m; i++)#define rep(i, n, m) for (int i = n; i < m; i++)#define sa(n) scanf("%d", &(n))const int maxn = 1e3 + 5;const ll mod = 1000000;const double PI = acos(-1.0);int n;int d[1 << 20];queue<int>que;void solve(){int i, j, k;int mask = 0;sa(n);rep(i, 0, n){sa(k);k--;mask |= ((k) << 2 * i);}rep(i, 0, 1 << 20){d[i] = INF;}d[mask] = 0;que.push(mask);while (!que.empty()){k = que.front();que.pop();if (k == 0)break;vector<int>b[4];rep(i, 0, n){b[(k >> (2 * i)) & 3].push_back(i);}rep(i, 0, 4){b[i].push_back(INF);}rep(i, 0, 4){rep(j, 0, 4){if (b[i][0] >= b[j][0]){continue;}int p = b[i][0];int to = k ^ ((i^j) << (2 * p));if (d[to] < INF){continue;}d[to] = d[k] + 1;que.push(to);}}}printf("%d\n", d[0]);}int main(){solve();return 0;}



0 0
原创粉丝点击