题目 HDU 2112
迪杰斯特拉最短路 实际上就是优先队列的广搜,每次提取队列中距离最小的进行搜索
AC代码如下,用了 map set 处理字符串很方便
#include<iostream>
#include<string>
#include<set>
#include<map>
#include<queue>
#include<vector>
#include<cstdio>
using namespace std;
const int maxn = 166;
int d[maxn];
vector< pair<int,int> > v[maxn];
void init(){
for(int i = 0;i < maxn;++i){
v[i].clear();
d[i] = 1 << 30;
}
}
int main(){
int n;
while(scanf("%d",&n) != EOF){
if(n == -1) break;
init();
set<string> S;
map<string,int> Map;
string str,str0;int ssize = 0;
cin >> str;S.insert(str);if(S.size() > ssize) Map[str] = ssize ++;
cin >> str0;S.insert(str0);if(S.size() > ssize) Map[str0] = ssize ++;
string str1,str2;int t;
for(int i = 0;i < n;++i){
cin >> str1 >> str2 >> t;
S.insert(str1);if(S.size() > ssize) Map[str1] = ssize ++;
S.insert(str2);if(S.size() > ssize) Map[str2] = ssize ++;
int a = Map[str1];
int b = Map[str2];
v[a].push_back(make_pair(b,t));
v[b].push_back(make_pair(a,t));
}
priority_queue< pair<int,int> > Q;
int st = Map[str];
d[st] = 0;Q.push(make_pair(-d[st],st));
while(!Q.empty()){
int now = Q.top().second;Q.pop();
for(int i = 0;i < v[now].size();++i){
int u = v[now][i].first;
if(d[u] > d[now]+v[now][i].second){
d[u] = d[now]+v[now][i].second;
Q.push(make_pair(-d[u],u));
}
}
}
int ed = Map[str0];
if(d[ed] == 1 << 30) printf("%d\n",-1);
else printf("%d\n",d[ed]);
}
return 0;
}