HDU TodayTime Limit: 15000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 10065 Accepted Submission(s): 2378
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
lcy
|
=====================================算法分析=====================================
Dijkstra+map。
=======================================代码=======================================
#include<map>
#include<queue>
#include<string>
#include<iostream>
using namespace std;
const int INF1=0x1f; //1字节整形最大值
const int INF4=0x1f1f1f1f; //4字节整形最大值
const int MAXN=155;
int N,Start,End,Edge[MAXN][MAXN],Dis[MAXN],SiteNum;
bool Vis[MAXN];
map<string,int> ToponymMap;
struct NODE
{
NODE(int P,int D) { Pt=P; Dis=D; }
friend bool operator < (const NODE& A,const NODE& B) { return A.Dis>B.Dis; }
int Pt,Dis;
};
int ToponymKey(string& toponym)
{
map<string,int>::iterator it;
it=ToponymMap.find(toponym);
if(it==ToponymMap.end())
{
return ToponymMap[toponym]=SiteNum++;
}
return it->second;
}
void Dijkstra()
{
memset(Vis,0,sizeof(Vis));
memset(Dis,INF1,sizeof(Dis));
priority_queue<NODE> q;
q.push(NODE(Start,Dis[Start]=0));
while(!q.empty())
{
NODE cur=q.top(); q.pop();
if(cur.Pt==End) { return; }
if(Vis[cur.Pt]) { continue; }
Vis[cur.Pt]=1;
for(int tmp=0;tmp<SiteNum;++tmp)
{
if(Edge[cur.Pt][tmp]<Dis[tmp]-cur.Dis)
{
Dis[tmp]=cur.Dis+Edge[cur.Pt][tmp];
q.push(NODE(tmp,Dis[tmp]));
}
}
}
}
void ReaData()
{
SiteNum=0;
memset(Edge,INF1,sizeof(Edge));
ToponymMap.clear();
string toponymS,toponymE;
cin>>toponymS>>toponymE;
Start=ToponymKey(toponymS);
End=ToponymKey(toponymE);
while(N--)
{
int t;
cin>>toponymS>>toponymE>>t;
int Key1=ToponymKey(toponymS);
int Key2=ToponymKey(toponymE);
if(t<Edge[Key1][Key2])
{
Edge[Key1][Key2]=t;
Edge[Key2][Key1]=t;
}
}
}
int main()
{
while(scanf("%d%*c",&N)==1&&N!=-1)
{
ReaData();
Dijkstra();
printf("%d\n",Dis[End]==INF4?-1:Dis[End]);
}
return 0;
}