HDU TodayTime Limit: 15000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 19366 Accepted Submission(s): 4552
Problem Description
经过锦囊相助,海东集团终于度过了危机,从此,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
Sample Output
Author
lgx
Source
Recommend
|
最短路,主要是把字符串处理的过程,而且题目中说的是无向图。
#include <stdio.h>
#include <math.h>
#include <vector>
#include <queue>
#include <string>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
#define INF 0x3f3f3f3f
using namespace std;
const int MAXN = 160;
int d[MAXN];
int cost[MAXN][MAXN];
bool used[MAXN];
int k,max_x;
struct Point{
char name[50];
int x;
}point[20020];
void comp(char S[])
{
strcpy(point[k].name,S);
for(int i=0;i<k;i++){
if(strcmp(point[i].name,point[k].name)==0){
point[k].x=point[i].x;
return;
}
}
point[k].x=max_x;
max_x++;
return;
}
void Dijkstra(int s)
{
for(int i=0;i<max_x;i++){
used[i]=false;
d[i]=INF;
}
d[s]=0;
while(true){
int v=-1;
for(int i=0;i<max_x;i++)
if(!used[i]&&(v==-1||d[v]>d[i])) v=i;
if(v==-1) break;
used[v]=true;
for(int i=0;i<max_x;i++)
d[i]=min(d[i],d[v]+cost[v][i]);
}
}
int main()
{
int N;
while(scanf("%d",&N),N!=-1){
Point star,last;
scanf("%s%s",star.name,last.name);
star.x=INF;last.x=INF;
char s1[50];
int time;
max_x=0;
k=0;
for(int i=0;i<MAXN;i++)
for(int j=0;j<MAXN;j++)
cost[i][j]=INF;
for(int i=0;i<N;i++){
scanf("%s",s1);
comp(s1);
k++;
scanf("%s",s1);
comp(s1);
scanf("%d",&time);
if(cost[point[k-1].x][point[k].x]>time){
cost[point[k].x][point[k-1].x]=time;
cost[point[k-1].x][point[k].x]=time;
}
k++;
}
int f1,f2;
f1=f2=0;
for(int i=0;i<k;i++){
if(f1&&f2)break;
if(!f1&&strcmp(point[i].name,star.name)==0){
star.x=point[i].x;
f1=1;
}
if(!f2&&strcmp(point[i].name,last.name)==0){
last.x=point[i].x;
f2=1;
}
}
if(strcmp(last.name,star.name)==0){
printf("0\n");
continue;
}
if(last.x==INF||star.x==INF){
printf("-1\n");
continue;
}
Dijkstra(star.x);
//printf("%d %d\n",star.x,last.x);
if(d[last.x]==INF)printf("-1\n");
else printf("%d\n",d[last.x]);
}
return 0;
}