hdu 5025 Saving Tang Monk(BFS+状态压缩)

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=5025

解题思路:

题目大意:

给你一个地图,孙悟空(K)救唐僧(T),地图中'S'表示蛇,第一次遇到时需要杀死蛇(蛇最多5条),多花费一分钟,'1'~'m'表示m个钥

匙(m<=9),孙悟空需要依次拿到这m个钥匙后,然后才能去救唐僧,集齐m个钥匙之前可以经过唐僧,集齐x个钥匙以前可以经过

x+1,x+2..个钥匙,问最少多少步才能救到唐僧。

算法思路:

经典的bfs+状态压缩的题,还有一点就是蛇的数量不多,可以直接压缩。。。

AC代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <map>
using namespace std;

typedef pair<int,int> pp;
const int INF = 0x3f3f3f3f;
map<pp,int> Hash;
int n,m,sx,sy,tx,ty,cntSnake;
char s[105][105];
int dx[] = {-1,0,1,0},dy[] = {0,-1,0,1};
int vis[105][105][10];
int ans;

bool judge(int x,int y){
    return 0 <= x && x < n && 0 <= y && y < n;
}
struct node{
    int x,y,key,snake,t;
    bool operator < (const node &b) const{
        return t > b.t;
    }
};

void bfs(){
    priority_queue<node> q;
    q.push((node){sx,sy,0,0,0});
    while(!q.empty()){
        node cur = q.top(),to;
        int x = cur.x,y = cur.y,key = cur.key,snake = cur.snake,t = cur.t;
        q.pop();
        if(s[x][y] == 'T' && key == m){
            ans = min(ans,cur.t);
            return ;
        }
        for(int i = 0;i < 4;++i){
            int xx = x+dx[i],yy = y + dy[i];
            if(!judge(xx,yy) || s[xx][yy] == '#')
                continue;
            if(s[xx][yy] == 'S'){
                pp tt = make_pair(xx,yy);
                if(snake & (1<<(Hash[tt]-1))){
                    to = (node){xx,yy,key,snake,t+1};
                }
                else{
                    int tosnake = snake | (1<<(Hash[tt]-1));
                    to = (node){xx,yy,key,tosnake,t+2};
                }
            }
            else if(s[xx][yy]-'0' == key + 1){
                to = (node){xx,yy,key+1,snake,t+1};
            }
            else{
                to = (node){xx,yy,key,snake,t+1};
            }
            if(to.t < vis[xx][yy][to.key]){
                q.push(to);
                vis[xx][yy][to.key] = to.t;
            }
        }
    }
}

int main(){
    while(scanf("%d%d",&n,&m),n+m){
        Hash.clear();
        cntSnake = 0;
        for(int i = 0; i < n; i++){
            scanf("%s",s[i]);
            for(int j = 0; j < n; j++){
                if(s[i][j] == 'K')
                    sx = i,sy = j;
                else if(s[i][j] == 'T')
                    tx = i,ty = j;
                else if(s[i][j] == 'S'){
                    pp tt = make_pair(i,j);
                    Hash[tt] = ++cntSnake;
                }
            }
        }
        memset(vis,INF,sizeof(vis));
        vis[sx][sy][0] = 0;
        ans = INF;
        bfs();
        if(ans >= INF)
            puts("impossible");
        else
            printf("%d\n",ans);
     }
     return 0;
 }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值