6 xiasha westlake xiasha station 60 xiasha ShoppingCenterofHangZhou 30 station westlake 20 ShoppingCenterofHangZhou supermarket 10 xiasha supermarket 50 supermarket westlake 10 -1
50 Hint: The best route is: xiasha->ShoppingCenterofHangZhou->supermarket->westlake
STL map + dijkstra
#include<iostream> #include<cstdio> #include<cstring> #include<map> #include<cmath> #include<vector> #include<algorithm> #include<set> #include<string> #include<queue> #include <stack> using namespace std; #pragma warning(disable : 4996) const int MAXN = 300; const int INF = 999999; int n; int maps[MAXN][MAXN]; bool visited[MAXN]; int dist[MAXN]; void init() { memset(visited, false, sizeof(visited)); for (int i = 1; i < MAXN; i++) { for (int j = 1; j < MAXN; j++) { if(i == j) { maps[i][j] = 0; } else { maps[i][j] = INF; } } } } void Dijkstra(int s, int e) //起点,终点 { int i, j; int minValue, minNode; dist[s] = 0; visited[s] = true; for (i = 1; i <= n; i++) { dist[i] = maps[s][i]; } for (i = 1; i <= n; i++) { minValue = INF; minNode = 0; for (j = 1; j <= n; j++) { if(!visited[j] && minValue > dist[j]) { minNode = j; minValue = dist[j]; } } if(minNode == 0) { break; } visited[minNode] = true; for (j = 1; j <= n; j++) { if(!visited[j] && maps[minNode][j] != INF && dist[j] > dist[minNode] + maps[minNode][j]) { dist[j] = dist[minNode] + maps[minNode][j]; } } if(minNode == e) { break; } } } int main() { freopen("in.txt", "r", stdin); char address[MAXN]; string str, Start, End; map<string, int>Map; int t, len, cnt, x, y; while (scanf("%d", &t) != EOF) { if(t == -1) { break; } Map.clear(); cnt = 1; cin >> Start >> End; init(); for(int i = 1; i <= t; i++) { scanf("%s", address); str = string(address); if(Map.find(str) == Map.end()) { Map[str] = cnt++; } x = Map[str]; scanf("%s", address); str = string(address); if(Map.find(str) == Map.end()) { Map[str] = cnt++; } y = Map[str]; scanf("%d", &len); if(maps[x][y] > len) { maps[x][y] = len; maps[y][x] = len; } } if(Map.find(Start) == Map.end() || Map.find(End) == Map.end()) { printf("-1\n"); } else { n = Map.size(); //cout << n << endl; x = Map[Start]; y = Map[End]; Dijkstra(x, y); if(dist[y] == INF) { printf("-1\n"); } else { printf("%d\n", dist[y]); } } } return 0; }