HDU Today
Time Limit: 15000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6832 Accepted Submission(s): 1650
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
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
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 using namespace std; 5 #define INF 0x7f7f7f7f 6 7 char pla[200][35], sta[35], end[35]; 8 int N, cnt, map[200][200], dis[200], hash[200], pre[200]; 9 10 int search( char name[] ) 11 { 12 for( int i= 0; i< cnt; ++i ) 13 if( !strcmp( pla[i], name ) ) 14 return i; 15 strcpy( pla[cnt], name ); 16 return cnt++; 17 } 18 19 void Dijkstra( ) 20 { 21 for( int i= 0; i< cnt; ++i ) 22 { 23 dis[i]= INF; 24 hash[i]= 0; 25 pre[i]= -1; 26 } 27 dis[0]= 0; 28 for( int i= 0; i< cnt; ++i ) 29 { 30 int pos= 0, min= INF; 31 for( int j= 0; j< cnt; ++j ) 32 if( !hash[j]&& dis[j]< min ) 33 { 34 pos= j; 35 min= dis[j]; 36 } 37 hash[pos]= 1; 38 if( pos== 1 ) 39 return ; 40 for( int j= 0; j< cnt; ++j ) 41 if( !hash[j]&& map[pos][j]!= INF ) 42 if( dis[j]> map[pos][j]+ dis[pos] ) 43 { 44 dis[j]= map[pos][j]+ dis[pos]; 45 pre[j]= pos; 46 } 47 } 48 } 49 void show(int i) 50 { 51 if(i==-1) 52 return; 53 show(pre[i]); 54 printf("%s->",pla[i]); 55 } 56 int main() 57 { 58 char ts[35], te[35]; int val; 59 while( scanf( "%d", &N ), N!= -1 ) 60 { 61 cnt= 0; 62 memset( pla, 0, sizeof( pla ) ); 63 memset( map, 0x7f, sizeof( map ) ); 64 scanf( "%s%s", sta, end ); 65 search( sta ),search( end ); 66 for( int i= 1; i<= N; ++i ) 67 { 68 scanf( "%s%s%d", ts, te, &val ); 69 int x= search( ts ), y= search( te ); 70 if( val< map[x][y] ) 71 map[y][x]= map[x][y]= val; 72 } 73 Dijkstra(); 74 if( dis[search( end )]!= INF ) 75 printf( "%d\n", dis[search( end )] ); 76 else 77 puts( "-1" ); 78 //show(search(end));输出路径 79 } 80 return 0; 81 }