一道最短路问题,关键是如何才能把字符串表示的地方之间的距离存放到整形的数组中一一对应,做好这一步以后套用最短路模板就OK啦~
6 xiasha westlake xiasha station 60 xiasha ShoppingCenterofHangZhou 30 station westlake 20 ShoppingCenterofHangZhou supermarket 10 xiasha supermarket 50 supermarket westlake 10 -1
50 Hint: The best route is: xiasha->ShoppingCenterofHangZhou->supermarket->westlake 虽然偶尔会迷路,但是因为有了你的帮助 **和**从此还是过上了幸福的生活。 ――全剧终――
#include <cstdio> #include <stdlib.h> #include <string.h> #include <algorithm> #define inf 0x5fffff using namespace std; int dis[250]; int map[250][250],visit[250]; char place[250][250]; int n,m; int s,e; void null( ) { for( int i=1 ; i<250 ; i++ ) for( int j=1 ; j<250 ; j++ ) map[i][j] = inf ; } int find( char c[50] ) { int i ; for( i=1 ; i<=m ; i++ ){ if( !strcmp( c , place[i] ) ) return i; } if( m == 0 || i > m ){ m++; strcpy( place[m] , c ); return m; } } void dijkstra( int s , int e ) { for( int i=1 ; i<=m ; i++ ){ dis[i] = map[s][i]; visit[i] = i == s ? 1 : 0; } for( int i=1 ; i<=m-1 ; i++ ){ int g = 0 ; dis[g] = inf; for( int j=1 ; j<=m ; j++ ){ if( !visit[j] && dis[j] < dis[g] ) g = j; } visit[g] = 1; for( int j=1 ; j<=m ; j++ ){ if( !visit[j] && map[g][j] + dis[g] < dis[j] ) dis[j] = map[g][j] + dis[g]; } } } int main( ) { char s1[50],s2[50]; int val; char start[50],end[50]; while( scanf("%d",&n) != EOF ){ if( n != -1 ){ null( ); m = 0; scanf("%s %s",start,end); for( int i=1 ; i<=n ; i++ ){ scanf("%s %s %d",s1,s2,&val); s = find( s1 ); e = find( s2 ); if( map[s][e] > val ){ map[s][e] = map[e][s] = val; } } // printf("m=%d\n",m); s = find( start ); e = find( end ); if( s == e ) printf("0\n"); else{ dijkstra( s , e ); if( dis[e] != inf ) printf("%d\n",dis[e]); else printf("-1\n"); } } } return 0; }