优先级队列+BFS。
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <queue> 5 using namespace std; 6 7 #define MAXN 25 8 9 typedef struct node_st { 10 int x, y, t; 11 node_st() {} 12 node_st(int xx, int yy, int tt) { 13 x = xx; y = yy; t = tt; 14 } 15 friend bool operator < (node_st a, node_st b) { 16 return a.t > b.t; 17 } 18 } node_st; 19 20 char map[MAXN][MAXN]; 21 int visit[MAXN][MAXN]; 22 int dir[4][2] = {-1,0,1,0,0,-1,0,1}; 23 int n, m, vp, vs, vt; 24 int sx, sy, ex, ey; 25 26 bool outRange(int x, int y) { 27 if (x<0 || x>=n || y<0 || y>=m) 28 return true; 29 return false; 30 } 31 32 int bfs() { 33 int i, x, y, t; 34 priority_queue<node_st> que; 35 node_st node; 36 37 if (map[ex][ey] == ‘@‘) 38 return -1; 39 40 memset(visit, 0, sizeof(visit)); 41 map[sx][sy] = ‘@‘; 42 que.push(node_st(sx, sy, 0)); 43 44 while (!que.empty()) { 45 node = que.top(); 46 if (node.x==ex && node.y==ey) 47 return node.t; 48 que.pop(); 49 for (i=0; i<4; ++i) { 50 x = node.x + dir[i][0]; 51 y = node.y + dir[i][1]; 52 if (outRange(x, y) || map[x][y]==‘@‘) 53 continue; 54 if (map[x][y] == ‘T‘) 55 t = node.t + vt; 56 if (map[x][y] == ‘.‘) 57 t = node.t + vs; 58 if (map[x][y] == ‘#‘) 59 t = node.t + vp; 60 if (visit[x][y]==0 || visit[x][y]>t) { 61 que.push(node_st(x, y, t)); 62 visit[x][y] = t; 63 } 64 } 65 } 66 67 return -1; 68 } 69 70 int main() { 71 int i, t=0; 72 73 while (scanf("%d %d", &n, &m) != EOF) { 74 scanf("%d%d%d", &vp, &vs, &vt); 75 for (i=0; i<n; ++i) 76 scanf("%s", map[i]); 77 scanf("%d%d%d%d", &sx, &sy, &ex, &ey); 78 i = bfs(); 79 printf("Case %d: %d\n", ++t, i); 80 } 81 82 return 0; 83 }
【HDOJ】2425 Hiking Trip,布布扣,bubuko.com
时间: 2024-12-09 22:10:49