思路简单,就是建图然后调用dijkstra算法即可。直接上代码:
/* * hdu2425/win.cpp * Created on: 2012-11-3 * Author : ben */ #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <ctime> #include <iostream> #include <algorithm> #include <queue> #include <set> #include <map> #include <stack> #include <string> #include <vector> #include <deque> #include <list> #include <functional> #include <numeric> #include <cctype> using namespace std; int N; const int SIZE = 500; typedef int typec; const typec INF = 0x7fffffff; typec graph[SIZE][SIZE]; const int move[4][2] = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; inline int getVnum(const int &r, const int &c, const int &C) { return (r - 1) * C + c - 1; } typec dijistra(int s, int e) { int i, j, k; typec mind, minf, D[SIZE]; bool visited[SIZE]; for (i = 0; i < N; i++) { visited[i] = false; D[i] = graph[s][i]; } visited[s] = 1; D[s] = 0; for (i = 1; i < N; i++) { mind = INF; minf = INF; k = 0; for (j = 0; j < N; j++) { if (visited[j]) { continue; } if (D[j] < mind) { k = j; mind = D[j]; } } visited[k] = true; for (j = 0; j < N; j++) { if (!visited[j]) { if (D[k] < D[j] - graph[k][j]) { D[j] = D[k] + graph[k][j]; } } } } return D[e]; } int work(int R, int C) { int vp, vs, vt; scanf("%d%d%d", &vp, &vs, &vt); map<char, int> pathlen; pathlen['#'] = vp; pathlen['.'] = vs; pathlen['T'] = vt; const int MAXRC = 25; char g[MAXRC][MAXRC]; memset(g, '@', sizeof(g)); getchar(); for(int i = 1; i <= R; i++) { for(int j = 1; j <= C; j++) { g[i][j] = getchar(); } getchar(); } int sr, sc, tr, tc; scanf("%d%d%d%d", &sr, &sc, &tr, &tc); sr++, sc++, tr++, tc++; if(g[tr][tc] == '@') { return -1; } fill_n(*graph, SIZE * SIZE, INF); for(int i = 1; i <= R; i++) { for(int j = 1; j <= C; j++) { int cur = getVnum(i, j, C); graph[cur][cur] = 0; if(g[i][j] == '@') { continue; } for(int k = 0; k < 4; k++) { int x = i + move[k][0]; int y = j + move[k][1]; if(g[x][y] != '@') { int z = getVnum(x, y, C); graph[cur][z] = pathlen[g[x][y]]; } } } } N = R * C; int ret = dijistra(getVnum(sr, sc, C), getVnum(tr, tc, C)); return ret == INF ? -1 : ret; } int main() { #ifndef ONLINE_JUDGE freopen("data.in", "r", stdin); #endif int R, C, T = 1; while(scanf("%d%d", &R, &C) == 2) { printf("Case %d: %d\n", T++, work(R, C)); } return 0; }