hdu 2112 map+Dijkstra
很好的一道题。。。一次水过。。。不过效率不是很高。。都2000MS+了。。。orz
View Code
1 #include<iostream> 2 #include<map> 3 #include<string> 4 const int N=220; 5 const int inf=1000000; 6 using namespace std; 7 8 int visited[N]; 9 int edge[N][N]; 10 int dist[N]; 11 map<string,int>mp; 12 13 void Dijkstra(int v0,int v,int n){ 14 memset(visited,0,sizeof(visited)); 15 for(int i=1;i<=n;i++){ 16 dist[i]=edge[v0][i]; 17 } 18 dist[v0]=0; 19 visited[v0]=1; 20 for(int i=1;i<n;i++){ 21 int min=inf,u=v0; 22 for(int j=1;j<=n;j++){ 23 if(!visited[j]&&dist[j]<min){ 24 u=j,min=dist[j]; 25 } 26 } 27 if(min==inf)break; 28 visited[u]=1; 29 for(int k=1;k<=n;k++){ 30 if(!visited[k]&&dist[u]+edge[u][k]<dist[k]){ 31 dist[k]=dist[u]+edge[u][k]; 32 } 33 } 34 } 35 if(dist[v]==inf){ 36 printf("-1\n"); 37 }else 38 printf("%d\n",dist[v]); 39 } 40 41 42 int main(){ 43 int n; 44 while(scanf("%d",&n)!=EOF){ 45 if(n==-1)break; 46 mp.clear(); 47 char s1[100],s2[100]; 48 scanf("%s%s",s1,s2); 49 int count=0; 50 if(!mp[s1]){ 51 mp[s1]=++count; 52 } 53 if(!mp[s2]){ 54 mp[s2]=++count; 55 } 56 for(int i=1;i<=N;i++){ 57 for(int j=1;j<=N;j++){ 58 if(i==j){ 59 edge[i][j]=0; 60 }else 61 edge[i][j]=inf; 62 } 63 } 64 char st[100],ed[100]; 65 int len; 66 for(int i=1;i<=n;i++){ 67 scanf("%s%s%d",st,ed,&len); 68 if(!mp[st]){ 69 mp[st]=++count; 70 } 71 if(!mp[ed]){ 72 mp[ed]=++count; 73 } 74 if(edge[mp[st]][mp[ed]]>len) 75 edge[mp[st]][mp[ed]]=edge[mp[ed]][mp[st]]=len; 76 } 77 Dijkstra(mp[s1],mp[s2],mp.size()); 78 } 79 return 0; 80 }