标签:
http://acm.hdu.edu.cn/showproblem.php?pid=2112
Time Limit: 15000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 18334 Accepted Submission(s): 4335
1 #include<iostream> 2 #include<cstdio> 3 #include<map> 4 #include<string> 5 #include<cstring> 6 #define N 155 7 #define INF 0x1fffffff 8 using namespace std; 9 int mp[N][N]; 10 bool p[N]; 11 int dist[N]; 12 void dijk(int s , int n) 13 { 14 int i , j , k ; 15 for( i = 1 ; i <= n ;i++) 16 { 17 p[i] = false; 18 dist[i] = mp[s][i]; 19 } 20 p[s] = true; 21 dist[s] = 0; 22 for(i = 1 ; i < n ; i++) 23 { 24 int Min = INF; 25 int k = 0 ; 26 for( j = 1 ; j <= n ;j++) 27 { 28 if(!p[j]&&dist[j]<Min) 29 { 30 Min = dist[j]; 31 k = j; 32 } 33 } 34 if(Min==INF) return ; 35 p[k] = true; 36 for(j = 1 ; j <= n ;j++) 37 { 38 if(!p[j]&&mp[k][j]!=INF&&dist[j]>dist[k]+mp[k][j]) 39 dist[j] = dist[k]+mp[k][j]; 40 } 41 } 42 } 43 map < string ,int > city; 44 int main() 45 { 46 int n ; 47 while(~scanf("%d",&n)&&n!=-1) 48 { 49 int cnt = 1 ; 50 city.clear(); 51 string ss, tt; 52 cin>>ss>>tt; 53 if(city.find(ss)==city.end()) 54 city[ss] = cnt++; 55 if(city.find(tt)==city.end()) 56 city[tt] = cnt++; 57 int l ; 58 string s , t ; 59 for(int i = 0; i < N; i++) for(int j = 0; j < N; j++) mp[i][j] = ((i==j) ? 0 : INF); 60 for(int i = 0 ;i < n ;i++) 61 { 62 cin>>s>>t>>l; 63 if(city.find(s)==city.end()) 64 city[s] = cnt++; 65 if(city.find(t)==city.end()) 66 city[t] = cnt++; 67 int sid = city[s], tid = city[t];//这样会减少复杂度 68 //printf("%d %d\n",sid, tid); 69 if(mp[sid][tid] > l) mp[sid][tid] = mp[tid][sid] = l; 70 } 71 72 dijk(city[ss], city.size()); 73 if(dist[city[tt]]!=INF) 74 printf("%d\n",dist[city[tt]]); 75 else printf("-1\n"); 76 } 77 return 0 ; 78 }
标签:
原文地址:http://www.cnblogs.com/shanyr/p/4671751.html