题目链接:HDU 1242 Rescue
除了多源跟上道题是一样的。
#include <iostream> #include <queue> #include <cstring> #include <cstdio> using namespace std; const int MAX_N = 200 + 20; const int INF = (1 << 29); struct Point { int x, y, dis; friend bool operator < (Point a, Point b) { return a.dis > b.dis; } Point (int x = 0, int y = 0, int dis = 0) : x(x), y(y), dis(dis) {}; }; priority_queue <Point> Q; int vis[MAX_N][MAX_N]; char _map[MAX_N][MAX_N]; int fx[4] = {0, 1, 0, -1}; int fy[4] = {1, 0, -1, 0}; int N, M, res; void BFS() { int dx, dy; Point a; while(!Q.empty()) { a = Q.top(); if(_map[a.x][a.y] == 'a') { res = a.dis; return ; } Q.pop(); for(int i = 0; i < 4; i++) { dx = a.x + fx[i], dy = a.y + fy[i]; if(dx >= 0 && dy >= 0 && dx < N && dy < M && _map[dx][dy] != '#' && !vis[dx][dy]) { vis[dx][dy] = 1; if(_map[dx][dy] == 'x') Q.push(Point(dx, dy, a.dis + 2)); else Q.push(Point(dx, dy, a.dis + 1)); } } } } int main() { while(scanf("%d%d", &N, &M) != EOF) { memset(vis, 0, sizeof(vis)); res = INF; for(int i = 0; i < N; i++) { scanf("%s", _map[i]); for(int j = 0; j < M; j++) { if(_map[i][j] == 'r') { vis[i][j] = 1; Q.push(Point(i, j, 0)); } } } BFS(); if(res == INF) printf("Poor ANGEL has to stay in the prison all his life.\n"); else printf("%d\n", res); while(!Q.empty()) Q.pop(); } return 0; }