zoukankan      html  css  js  c++  java
  • HDU 6171 Admiral(双向BFS+队列)题解

    思路:

    最大步骤有20,直接BFS会超时。

    因为知道开始情况和结果所以可以用双向BFS,每个BFS规定最大步骤为10,这样相加肯定小于20。这里要保存每个状态搜索到的最小步骤,用Hash储存。当发现现有状态已经在另一路出现了,那么就输出两者相加的步骤和。

    代码:

    #include<iostream>
    #include<algorithm>
    #include<queue>
    #include<map>
    #define ll long long
    using namespace std;
    const int N = 100+5;
    int to[4][2] = {1,0,1,1,-1,0,-1,-1};   //下,右下,上,左上
    map<ll,int> s[2];
    struct node{
        int flag;
        int x,y;
        int p[6][6];
        int len;
    };
    ll Hash(node a){
        ll ans = 0;
        for(int i = 0;i < 6;i++){
            for(int j = 0;j <= i;j++){
                ans = ans*6 + a.p[i][j];
            }
        }
        return ans;
    }
    void BFS(node a,node b){
        s[0].clear();
        s[1].clear();
        queue<node> q;
        while(!q.empty()) q.pop();
        s[a.flag][Hash(a)] = 0;
        s[b.flag][Hash(b)] = 0;
        q.push(a);
        q.push(b);
        while(!q.empty()){
            a = q.front();
            q.pop();
            if(s[!a.flag].count(Hash(a))){
                int ans = s[!a.flag][Hash(a)] + a.len;
                printf("%d
    ",ans);
                return;
            }
            for(int i = 0;i < 4;i++){
                b = a;
                b.x += to[i][0];
                b.y += to[i][1];
                if(b.x < 0 || b.y < 0 || b.y > b.x || b.x > 5) continue;
                swap(b.p[b.x][b.y],b.p[a.x][a.y]);
                ll num = Hash(b);
                if(s[b.flag].count(num)) continue;
                b.len += 1;
                if(b.len <= 10){
                    s[b.flag][num] = b.len;
                    q.push(b);
                }
            }
        }
        printf("too difficult
    ");
    }
    int main(){
        int T,cnt,tp;
        node a,b;
        scanf("%d",&T);
        while(T--){
           for(int i = 0;i <= 5;i++){
            for(int j = 0;j <= i;j++){
                scanf("%d",&a.p[i][j]);
                if(a.p[i][j] == 0) a.x = i,a.y = j;
                b.p[i][j] = i;  //最后
            }
           }
           a.flag = 0,a.len = 0;
           b.x = b.y = b.len = 0,b.flag = 1;
           BFS(a,b);
        }
        return 0;
    }
    
    


  • 相关阅读:
    Android开发学习之路-使用Handler和Message更新UI
    Android开发学习之路-Service和Activity的通信
    Android开发学习之路-自定义ListView(继承BaseAdapter)
    URI、URL、URN
    理解 node.js 的事件循环
    创建hexo风格的markdown页面
    heroku
    js通过沿着作用域链还是原型链查找变量
    浏览器中实现3D全景浏览
    数据可视化图表ECharts
  • 原文地址:https://www.cnblogs.com/KirinSB/p/9408792.html
Copyright © 2011-2022 走看看