Time Limit: 15000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 19475 Accepted Submission(s): 4574
1 #include<stdio.h> 2 #include<string.h> 3 #define MIN(x,y)(x<y?x:y) 4 #include<map> 5 #include<string> 6 using namespace std; 7 const int MAXN=160; 8 const int INF=0x3f3f3f3f; 9 int N,top; 10 map<string,int>mp; 11 int bus[MAXN][MAXN],vis[MAXN],d[MAXN]; 12 void initial(){ 13 memset(bus,INF,sizeof(bus)); 14 memset(vis,0,sizeof(vis)); 15 memset(d,INF,sizeof(d)); 16 mp.clear(); 17 top=0; 18 } 19 void dijskra(int s){ 20 d[s]=0; 21 int k; 22 while(true){ 23 k=-1; 24 for(int i=0;i<top;i++) 25 if(!vis[i]&&(k==-1||d[i]<d[k]))k=i; 26 if(k==-1)break; 27 vis[k]=1; 28 for(int i=0;i<top;i++) 29 d[i]=MIN(d[i],d[k]+bus[k][i]); 30 } 31 } 32 int main(){ 33 char beg[31],en[31],a[31],b[31]; 34 int c; 35 while(~scanf("%d",&N),N!=-1){ 36 initial(); 37 scanf("%s%s",beg,en); 38 while(N--){ 39 scanf("%s%s%d",a,b,&c); 40 if(!mp.count(a))mp[a]=top++; 41 if(!mp.count(b))mp[b]=top++; 42 if(c<bus[mp[a]][mp[b]]) 43 bus[mp[a]][mp[b]]=bus[mp[b]][mp[a]]=c;//无向图。。。。 44 } 45 if(!strcmp(beg,en)){//考虑的真全面。。。当位置相同时0.。 46 puts("0"); 47 continue; 48 } 49 if(!mp.count(beg)||!mp.count(en)){//当没有到开始结束时的车时-1 50 puts("-1"); 51 continue; 52 } 53 dijskra(mp[beg]); 54 //if(!strcmp(beg,en))puts("1"); 55 if(d[mp[en]]==INF)puts("-1"); 56 else printf("%d\n",d[mp[en]]); 57 } 58 return 0; 59 }
原文:http://www.cnblogs.com/handsomecui/p/4737255.html