题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2112
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 虽然偶尔会迷路,但是因为有了你的帮助 **和**从此还是过上了幸福的生活。 ――全剧终――
#pragma warning (disable:4786) #include <cstdio> #include <cmath> #include <cstring> #include <string> #include <cstdlib> #include <climits> #include <ctype.h> #include <queue> #include <stack> #include <vector> #include <deque> #include <set> #include <map> #include <iostream> #include <algorithm> using namespace std; #define PI acos(-1.0) #define INF 0x3fffffff //typedef long long LL; //typedef __int64 LL; #define MAXN 10017 #define M 32 int mat[MAXN][MAXN]; int n; #define MAX 150 map<string,int>m; void init() { for(int i = 0; i <= MAX; i++) { for(int j = 0; j <= MAX; j++) { if(i == j) mat[i][j] = 0; else mat[i][j] = INF; } } m.clear(); } int dijkstra (int s,int f) { //s为起点, f:为终点 int dis[MAXN];//记录到任意点的最短距离 int mark[MAXN];//记录被选中的结点 int i,j,k = 0; for(i = 0; i <= MAX; i++) { mark[i] = 0;//初始化所有结点,每个结点都没有被选中 dis[i] = INF; } mark[s] = 1;//start结点被选中 dis[s] = 0;//将start结点的的距离设置为0 int min ;//设置最短的距离。 for(i = 1; i <= MAX; i++) { k = 1; min = INF; for(j = 1; j <= MAX; j++) { if(mark[j] == 0 && dis[j] < min)//未被选中的结点中,距离最短的被选中 { min = dis[j] ; k = j; } } mark[k] = 1;//标记为被选中 for(j = 1; j <= MAX; j++) { if( mark[j] == 0 && (dis[j] > (dis[k] + mat[k][j])))//修改剩余结点的最短距离 { dis[j] = dis[k] + mat[k][j]; } } } return dis[f]; } int main() { int i; char s[M], e[M], a[M], b[M]; int v; while(~scanf("%d",&n)) { init(); if(n == -1) break; scanf("%s%s",s,e); m[s] = 1; if(!m[e]) m[e] = 2; int c = 3; for(i = 0; i < n; i++) { scanf("%s%s%d",a,b,&v); if(!m[a]) m[a] = c++; if(!m[b]) m[b] = c++; if(v < mat[m[a]][m[b]]) { mat[m[a]][m[b]] = v; mat[m[b]][m[a]] = v; } } int ans = dijkstra(m[s],m[e]); if(ans == INF) printf("-1\n"); else printf("%d\n",ans); } return 0; }
HDU 2112 HDU Today(Dijkstra),布布扣,bubuko.com
原文:http://blog.csdn.net/u012860063/article/details/38380395