对于一个长度为15数组,每个元素1<=ai<=15.问你这个数组的hash值。
如果对ai没有其他限制,那么这个数组的hash值应该这样计算
ll hash = 0;
for(int i = 0;i<15;i++)
hash+=a[i],hash*=15;
如果ai两两之间不相等,也就是1到15都出现且只出现一次,那么这个数组的hash值应该这样计算
ll hash = 0;
for(int i = 0;i<15;i++)
hash+=a[i],hash*=2;
为什么是乘2不是乘15呢,仔细想想就明白了;
题意:
给你一个4*8的棋盘,每个格子可能是空格,也可能有一个值ai,j,ai,j = i * 4 + j,(1<=i<=4,1<=j<=7,且任意两个格子的值互不相等,每个可能的值都出现一次。),你可以把某个数字移动到某个空格,空格是任意的,但这个数字要等于要移动的空格左边的数字的值加1,给你初始局面,你可以先把第一列填好(先把11,21,31,41这四个数跟到第一列对应位置的数互换,这个操作不计算入步数),然后问你最少多少步可以到这个局面。
输入
4
12 13 14 15 16 17 21
22 23 24 25 26 27 31
32 33 34 35 36 37 41
42 43 44 45 46 47 11
26 31 13 44 21 24 42
17 45 23 25 41 36 11
46 34 14 12 37 32 47
16 43 27 35 22 33 15
17 12 16 13 15 14 11
27 22 26 23 25 24 21
37 32 36 33 35 34 31
47 42 46 43 45 44 41
27 14 22 35 32 46 33
13 17 36 24 44 21 15
43 16 45 47 23 11 26
25 37 41 34 42 12 31
输出
0
33
60
-1
思路:
暴力bfs,然后记录走过的局
面的hash值,求hash值的方法前面已经写过了(poj不能用unordered_map,用map也能ac)
代码
#include <iostream>
#include <cstdio>
#include <iomanip>
#include <string>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <set>
#include <vector>
#include <map>
#include <algorithm>
#include <cmath>
#include <stack>
//#include <unordered_map>
//#include <hash_map>
#define INF 0x3f3f3f3f
#define LINF 0x3f3f3f3f3f3f3f3f
#define ll long long
#define ull unsigned long long
#define uint unsigned int
using namespace std;
struct board {
int val[4][8],times;
void init() {
memset(val, 0, sizeof(val)); times = 0;
for (int i = 0; i < 4; i++)
val[i][0] = (i + 1) * 10 + 1;
}
bool is_right() {
bool flag = true;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 7; j++)
if (val[i][j] != (i + 1) * 10 + j + 1)
flag = false;
return flag;
}
bool board_move(int x, int y) {
if (val[x][y] != 0 ||
val[x][y - 1] == 0 ||
val[x][y - 1] % 10 == 7)
return false;
times++;
int dir = val[x][y - 1] + 1;
for (int i = 0; i < 4; i++)
for (int j = 1; j < 8; j++)
if (val[i][j] == dir)
val[i][j] = 0;
val[x][y] = dir;
return true;
}
}demo;
ll get_hash(board x) {
ll now = 0;
for (int i = 0; i < 4; i++)
for (int j = 0; j < 8; j++)
now += x.val[i][j], now *= 2;
return now;
}
int bfs() {
if (demo.is_right())
return 0;
board temp = demo;
board now;
map<ll, int> mmap;
queue<board> que;
que.push(temp);
mmap[get_hash(temp)] = 1;
while (!que.empty()) {
temp = que.front();
que.pop();
for (int i = 0; i < 4; i++)
for (int j = 1; j < 8; j++) {
now = temp;
if (now.board_move(i, j)) {
if (now.is_right())
return now.times;
if (mmap.find(get_hash(now)) == mmap.end()) {
que.push(now);
mmap[get_hash(now)] = 1;
}
}
}
}
return -1;
}
int main() {
int t;
scanf("%d", &t);
while (t--) {
demo.init();
for (int i = 0; i < 4; i++)
for (int j = 1; j < 8; j++) {
scanf("%d", &demo.val[i][j]);
if (demo.val[i][j] % 10 == 1)
demo.val[i][j] = 0;
}
printf("%d\n", bfs());
}
return 0;
}