您的位置:首页 > 产品设计 > UI/UE

HDU 1242 Rescue (广搜 + 优先队列)

2016-03-30 21:28 218 查看
HDU 1242

学会了优先队列的使用,就是要把用时最少的方案放在队列最前面。

关于对 < 的重载不是很懂,好像只要a > b 就是把小的放在队前,即最小堆,感觉好像和sort相反。。

参考博客:/article/8151429.html

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
int N, M;
const int inf = 0x3f3f3f3f;
int map[210][210], vis[210][210];
int sx, sy;
int ans;
struct node {
int x, y, time;
friend bool operator < (node a, node b) {
return a.time > b.time;
}
};
int dir[4][2] = {0, 1, 1, 0, 0, -1, -1, 0};
void bfs() {
priority_queue<node> q;
node now, next;
now.time = 0, now.x = sx, now.y = sy;
q.push(now);
vis[sx][sy] = 1;
while(!q.empty()) {
now = q.top();
q.pop();
if(map[now.x][now.y] == 'r') {
ans = now.time;
return;
}
int i;
for(i = 0; i < 4; i++) {
next.x = now.x + dir[i][0];
next.y = now.y + dir[i][1];
next.time = now.time;
if(next.x >= 0 && next.x < N && next.y >= 0 && next.y < M && map[next.x][next.y] != '#' && vis[next.x][next.y] == 0) {
vis[next.x][next.y] = 1;
if(map[next.x][next.y] == 'x') next.time += 2;
else next.time += 1;
q.push(next);
}
}
}
}
int main() {
while(~scanf("%d %d", &N, &M)) {
getchar();
int i, j;
for(i = 0; i < N; i++) {
for(j = 0; j < M; j++) {
scanf("%c", &map[i][j]);
if(map[i][j] == 'a') {
sx = i, sy = j;
}
}
getchar();
}
memset(vis, 0, sizeof(vis));
ans = inf;
bfs();
if(ans == inf) printf("Poor ANGEL has to stay in the prison all his life.\n");
else printf("%d\n", ans);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: