赤裸裸的,需要注意的是这题是无向图,有重边,且起点可能与终点相同,这些是容易WA的地方。
/* * hdu2112/win.cpp * Created on: 2012-8-2 * Author : ben */ #include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <ctime> #include <iostream> #include <algorithm> #include <queue> #include <set> #include <stack> #include <string> #include <vector> #include <deque> #include <list> #include <functional> #include <numeric> #include <cctype> using namespace std; int N, M; const int SIZE = 160; typedef int typec; const typec MAX = 0x7fffffff; typec map[SIZE][SIZE]; char stations[SIZE][40]; 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] = map[s][i]; } visited[s] = 1; D[s] = 0; for (i = 1; i < N; i++) { mind = MAX; minf = MAX; 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] - map[k][j]) { D[j] = D[k] + map[k][j]; } } } } return D[e]; } int getindex(const char *name) { for(int i = 0; i < N; i++) { if(strcmp(name, stations[i]) == 0) { return i; } } strcpy(stations[N], name); return N++; } void init() { for (int i = 0; i < SIZE; i++) { for (int j = 0; j < SIZE; j++) { map[i][j] = MAX; } } } int main() { #ifndef ONLINE_JUDGE freopen("data.in", "r", stdin); #endif char ts[40]; int t, a, b, s, e; while(scanf("%d", &M) == 1 && M > 0) { init(); N = 0; scanf("%s", ts); s = getindex(ts); scanf("%s", ts); e = getindex(ts); for(int i = 0; i < M; i++) { scanf("%s", ts); a = getindex(ts); scanf("%s", ts); b = getindex(ts); scanf("%d", &t); if(t < map[a][b]) { map[a][b] = map[b][a] = t; } } int ans = dijistra(s, e); printf("%d\n", ans < MAX ? ans : -1); } return 0; }