HDU 6171 Admiral 双向搜索(meet in the middle) + 哈希

20 篇文章 0 订阅
7 篇文章 0 订阅

传送门:HDU6171

题意:给你一个高度为6的数塔,问最少多少步能走成如下状态。
每次只能将值为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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值