HDU 6171 Admiral

HDU 6171 Admiral

搜索,双向宽搜

题意

自己读题吧。不过有两点注意:每次只能把0数字和其他数字交换;每个数字的可交换范围是左上,正上,正下,右下。

思路

不会搜索啊。。。%%%
因为起始状态与终止状态都很明确,考虑双向宽搜。关于状态的表示与检查:作为6进制数哈希,用个map记录状态与达到该状态对应的步数。因为是双向搜索,所以开两个map记录。

双向宽搜就是从初始状态搜,记录到map1;从终止状态搜,记录到map2。从队列里取出一个状态,枚举他的四个可转移状态,如果他的对立队列有,说明另一侧已经搜到了这个状态,直接返回即可,否则继续搜索。

代码

#include<bits\stdc++.h>
#define M(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef unsigned long long ull;
struct State
{
    int mp[6][6];
    int zposx, zposy;
    bool fl;
    int stp;
    State(){}
    State(const State &no)
    {
        memcpy(mp, no.mp, sizeof(mp));
        zposx=no.zposx, zposy=no.zposy;
        fl=no.fl, stp=no.stp;
    }
    ull hash()
    {
        ull tmp=0;
        for(int i=0;i<6;i++)
            for(int j=0;j<=i;j++)
                tmp=tmp*6+mp[i][j];
        return tmp;
    }
}s, t;
int go[4][2]={{-1, -1}, {-1, 0}, {1, 0}, {1, 1}};
map<ull, int> hatostp[2];
queue<State> que;

int bfs(State &s, State &t)
{
    while(!que.empty()) que.pop();
    ull has=s.hash(), hat=t.hash();
    hatostp[0].clear(), hatostp[1].clear();
    hatostp[0][has]=0, hatostp[1][hat]=0;
    que.push(s), que.push(t);
    while(!que.empty())
    {
        State now=que.front();que.pop();
        ull tmp;
        if(hatostp[!now.fl].count(tmp=now.hash()))
        {
            if(hatostp[!now.fl][tmp]+now.stp<=20)
                return hatostp[!now.fl][tmp]+now.stp;
            else continue;
        }
        if(now.stp>=10) continue;
        for(int i=0;i<4;i++)
        {
            State ne(now);
            ne.zposx+=go[i][0], ne.zposy+=go[i][1];
            if(ne.zposx<0||ne.zposx>5||ne.zposy<0||ne.zposy>ne.zposx) 
                continue;
            swap(ne.mp[ne.zposx][ne.zposy], ne.mp[now.zposx][now.zposy]);
            tmp=ne.hash();
            if(hatostp[ne.fl].count(tmp)) continue;
            hatostp[ne.fl][tmp]=++ne.stp;
            que.push(ne);
        }
    }
    return -1;
}

int main()
{
    int T;scanf("%d", &T);
    while(T--)
    {
        for(int i=0;i<6;i++)
        {
            for(int j=0;j<=i;j++)
            {
                int tmp;
                scanf("%d", &tmp);
                s.mp[i][j]=tmp;
                if(tmp==0) s.zposx=i, s.zposy=j;
                t.mp[i][j]=i;
            }
        }
        t.zposx=0, t.zposy=0;
        s.fl=0, t.fl=1;
        s.stp=t.stp=0;

        int res=bfs(s, t);
        if(res==-1) puts("too difficult");
        else printf("%d\n", res);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值