HDU Today
经过锦囊相助,海东集团终于度过了危机,从此,HDU的发展就一直顺风顺水,到了2050年,集团已经相当规模了,据说进入了钱江肉丝经济开发区500强。这时候,XHD夫妇也退居了二线,并在风景秀美的诸暨市浬浦镇陶姚村买了个房子,开始安度晚年了。
这样住了一段时间,徐总对当地的交通还是不太了解。有时很郁闷,想去一个地方又不知道应该乘什么公交车,在什么地方转车,在什么地方下车(其实徐总自己有车,却一定要与民同乐,这就是徐总的性格)。
徐总经常会问蹩脚的英文问路:“Can you help me?”。看着他那迷茫而又无助的眼神,热心的你能帮帮他吗?
请帮助他用最短的时间到达目的地(假设每一路公交车都只在起点站和终点站停,而且随时都会开)。
Input
输入数据有多组,每组的第一行是公交车的总数N(0<=N<=10000);
第二行有徐总的所在地start,他的目的地end;
接着有n行,每行有站名s,站名e,以及从s到e的时间整数t(0< t <100)(每个地名是一个长度不超过30的字符串)。
note:一组数据中地名数不会超过150个。
如果N==-1,表示输入结束。
Output
如果徐总能到达目的地,输出最短的时间;否则,输出“-1”。
Sample Input
6
xiasha westlake
xiasha station 60
xiasha ShoppingCenterofHangZhou 30
station westlake 20
ShoppingCenterofHangZhou supermarket 10
xiasha supermarket 50
supermarket westlake 10
-1
Sample Output
50
Hint:
The best route is:
xiasha->ShoppingCenterofHangZhou->supermarket->westlake
虽然偶尔会迷路,但是因为有了你的帮助
和从此还是过上了幸福的生活。
――全剧终――
题目链接:https://cn.vjudge.net/contest/242149#problem/F
是个求图中最短路的问题,也是可以用Dijkstra的,其中还需要map。但有几个点需要注意一下,题目里面没有说他一定是从一个地方去往另一个不同的地方,也就是说两个地方有可能相同,所以需要判断一下,还有就是到不了的情况,在算法里面判断一下他最后出队的是不是他想要去的地方就可以了。
#include<cstdio>
#include<iostream>
#include<map>
#include<string>
#include<queue>
#include<cstring>
using namespace std;
const int maxn = 1e6+5;
map<string, int> mp;
struct edge
{
int to;
int w;
int ne;
} e[maxn];
struct node
{
int pos;
int cost;
node(){}
node(int pos,int cost):pos(pos),cost(cost){}
friend bool operator < (node a,node b)
{
return a.cost> b.cost;
}
};
int cnt, p;
int N, W;
int head[maxn],dis[maxn],book[maxn];
void add(int u,int v,int w)
{
e[cnt].to = v;
e[cnt].w = w;
e[cnt].ne = head[u];
head[u] = cnt++;
}
void init()
{
cnt = p = 0;
memset(dis, 0x3f3f3f3f, sizeof(dis));
memset(book, 0, sizeof(book));
memset(head, -1, sizeof(head));
}
void dijkstra(int sx, int ex)
{
priority_queue<node> q;
dis[sx] = 0;
q.push(node(sx, 0));
int record;
while(q.size())
{
node temp = q.top();
q.pop();
if(book[temp.pos]) continue ;
book[temp.pos] = 1;
record = temp.pos;
if(temp.pos == ex) break ;
for(int i = head[temp.pos]; i != -1; i = e[i].ne)
if(dis[e[i].to] > dis[temp.pos] + e[i].w)
{
dis[e[i].to] = dis[temp.pos] + e[i].w;
q.push(node(e[i].to, dis[e[i].to]));
}
}
if(record != ex) printf("-1\n");
else printf("%d\n", dis[ex]);
}
int main()
{
while(scanf("%d", &N), N != -1)
{
mp.clear();
init();
string s, t;
cin >> s >> t;
mp[s] = ++p; if(!mp[t]) mp[t] = ++p;
for(int i = 0; i < N; i++)
{
string u, v;
cin >> u >> v;
scanf("%d", &W);
if(!mp[u]) mp[u] = ++p;
if(!mp[v]) mp[v] = ++p;
add(mp[u], mp[v], W);
add(mp[v], mp[u], W);
}
if(mp[s] == mp[t])
{
printf("0\n");
continue ;
}
dijkstra(mp[s], mp[t]);
}
return 0;
}