传送门:HDU6171
题意:给你一个高度为6的数塔,问最少多少步能走成如下状态。
每次只能将值为0的点与其左上方,上方,下方,右下方四个方向的一个点进行交换。
0
1 1
2 2 2
3 3 3 3
4 4 4 4 4
5 5 5 5 5 5
大于20步可以直接输出“too difficult”
思路:比赛的时候智障的想了一个多少小时的A* 和 IDA* ,还想了很长时间该怎么Hash实现O(1)book,结果tmd双向搜索就行。。而且加上xjb哈希一下然后加个map来book的复杂度也跑的快的飞起。。这不科学啊。。
代码:
#include<bits/stdc++.h>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
typedef pair<int,int> P;
const int MAXN = 100010;
typedef unsigned long long ull;
struct node{
int val[6][6];
int r, c; // 0所在的位置
bool tp;
int step;
};
ull Hash(node &t)
{
ull tmp = 0;
for(int i = 0; i < 6; i++)
{
for(int j = 0; j <= i; j++)
tmp = tmp * 6 + t.val[i][j];
}
return tmp;
}
map<ull, int> book[2];
queue<node> q;
int go[4][2] = {-1, -1, -1, 0, 1, 0, 1, 1};
int bfs(node &s, node &t)
{
while(!q.empty()) q.pop();
book[0].clear();
book[1].clear();
s.tp = 0;
t.tp = 1;
s.step = t.step = 0;
book[s.tp][Hash(s)] = 0;
book[t.tp][Hash(t)] = 0;
q.push(s);
q.push(t);
while(!q.empty())
{
node e = q.front(), x; q.pop();
ull tmp = Hash(e);
if(book[!e.tp].count(tmp))
if(book[!e.tp][tmp] + e.step <= 20)
return book[!e.tp][tmp]+ e.step;
else
continue;
if(e.step >= 10) continue; //因为是双向搜索,所以限制是20/2
for(int i = 0; i < 4; i++)
{
x = e;
x.r += go[i][0];
x.c += go[i][1];
if(x.r >= 6 || x.c > x.r || x.c < 0 || x.r < 0) continue;
swap(x.val[x.r][x.c], x.val[e.r][e.c]);
tmp = Hash(x);
if(book[x.tp].count(tmp)) continue;
book[x.tp][tmp] = ++x.step;
q.push(x);
}
}
return -1;
}
int main()
{
int T;
cin >> T;
node s, t;
while(T--)
{
for(int i = 0; i < 6; i++)
for(int j = 0; j <= i; j++)
{
scanf("%d", &s.val[i][j]);
if(s.val[i][j] == 0)
{
s.r = i;
s.c = j;
}
t.val[i][j] = i;
}
t.r = 0, t.c = 0;
int ans = bfs(s, t);
if(ans == -1)
puts("too difficult");
else
printf("%d\n", ans);
}
return 0;
}