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 虽然偶尔会迷路,但是因为有了你的帮助 **和**从此还是过上了幸福的生活。 ――全剧终――
解析:也是Dijkstra算法,只不过这里给的点不是编号了,而是字符串,也一样的,只需要用map把各个字符串映射成编号即可。
AC代码:
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <map>
using namespace std;
#define INF 1e7 + 2
int n;
int w[155][155], d[155], v[155];
void dijkstra(int s){
memset(v, 0, sizeof(v));
for(int i=1; i<=n; i++) d[i] = i==s ? 0 : INF;
for(int i=1; i<=n; i++){
int x, m = INF;
for(int y=1; y<=n; y++)
if(!v[y] && d[y] <= m) m = d[x = y];
v[x] = 1;
for(int y=1; y<=n; y++) d[y] = min(d[y], d[x] + w[x][y]);
}
}
int main(){
// freopen("in.txt", "r", stdin);
int x, y, z;
map<string, int> a;
while(scanf("%d", &n)!=EOF && n!=-1){
string s, e, from, to;
int cnt = 0;
cin >> from >> to;
a[from] = ++cnt;
if(a.find(to) == a.end()) a[to] = ++cnt; //不存在,才加新点,编号+1
for(int i=1; i<155; i++)
for(int j=1; j<155; j++)
w[i][j] = i==j ? 0 : INF;
for(int i=0; i<n; i++){
cin >> s >> e >> z;
if(a.find(s) == a.end()) a[s] = ++cnt;
if(a.find(e) == a.end()) a[e] = ++cnt;
x = a[s], y = a[e];
w[x][y] = w[y][x] = min(w[x][y], z);
}
n = cnt; //一定不要忘了,cnt代表的是结点总数,Dijkstra里面会用到
dijkstra(1);
printf("%d\n", d[ a[to] ]==INF ? -1 : d[ a[to] ]);
a.clear();
}
return 0;
}
PS:里面还涉及到map的用法,map还是很好用的。在map< , > a中查找,直接用它的成员函数a.find(key)即可,里面参数是第一个关键字,返回的是关键字所在迭代器,如果不存在,返回的迭代器就是a.end()。
hdu 2112 HDU Today (Dijkstra + map)
原文:http://blog.csdn.net/u013446688/article/details/42872109