单源最短路,Dijkstra算法
只需把每一个字符串地址对应一个数字即可,可以用map来实现
#include <cstdio> #include <map> #include <string> #include <algorithm> #include <cstring> #include <iostream> #define INF 999999999 #define MAX 200 using namespace std; int s[MAX],n[MAX]; int dist[MAX],ans[MAX][MAX]; void Dijkstra(int n,int v) { int newdist,temp,u,i,j; for(i=v;i<=n;i++) { dist[i]=ans[v][i]; s[i]=0; } dist[v]=0; s[v]=1; for(i=v;i<=n;i++) { temp=INF; u=v; for(j=v;j<=n;j++) if((!s[j])&&(dist[j]<temp)) { u=j; temp=dist[j]; } s[u]=1; for(j=v;j<=n;j++) if((!s[j])&&(ans[u][j]<INF)) { newdist=dist[u]+ans[u][j]; if(newdist<dist[j]) dist[j]=newdist; } } } int main() { char start[35],end[35]; char a[35],b[35]; int N,t,i,k; bool flag; map<string,int> station; while(scanf("%d",&N)!=-1&&N!=-1) { station.clear(); flag=false; for(int i=0;i<160;i++) for(int j=0;j<=160;j++) ans[i][j]=INF; scanf("%s%s",start,end); station[start]=1; station[end]=2; k=3; if(strcmp(start,end)==0) flag=true; for(i=0;i<N;i++) { scanf("%s%s%d",a,b,&t); if(!station[a]) station[a]=k++; if(!station[b]) station[b]=k++; ans[station[a]][station[b]]=ans[station[b]][station[a]]=t; } if(flag) puts("0"); else { k--; Dijkstra(k,1); if(dist[2]==INF) puts("-1"); else printf("%d\n",dist[2]); } } return 0; }