HDU 1242
学会了优先队列的使用,就是要把用时最少的方案放在队列最前面。
关于对 < 的重载不是很懂,好像只要a > b 就是把小的放在队前,即最小堆,感觉好像和sort相反。。
参考博客:http://blog.csdn.net/cambridgeacm/article/details/7725146
#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; }