裸的最短路,只是记录节点的时候利用map来存储。特判,起点和终点相同的时候输出0。
#include <stdio.h>
#include <queue>
#include <map>
#include <string>
#include <string.h>
#include <algorithm>
using namespace std;
const int INF=10000000;
int main(){
int n;
while(scanf("%d",&n)!=EOF){
if(n==-1) break;
map<string,int>m;
m.clear();
char st[155],ed[155],s1[155],s2[155];
bool tag=false,ff1=false,ff2=false;
int tot=0,edge[155][155];
for(int i=0;i<155;i++)
for(int j=0;j<155;j++)
edge[i][j]=i==j?0:INF;
scanf("%s%s",st,ed);
if(strcmp(st,ed)==0)
tag=true;//判断起点和终点是否相同
if(!m.count(st))
m[st]=tot++;
if(!m.count(ed))
m[ed]=tot++;
for(int i=0;i<n;i++){
int d;
scanf("%s%s%d",s1,s2,&d);
if(!strcmp(s1,st)||!strcmp(s2,st))
ff1=true;
if(!strcmp(s1,ed)||!strcmp(s2,ed))
ff2=true;//判断是否存在起点或终点
if(!m.count(s1))
m[s1]=tot++;
if(!m.count(s2))
m[s2]=tot++;
edge[m[s1]][m[s2]]=min(edge[m[s1]][m[s2]],d);
edge[m[s2]][m[s1]]=edge[m[s1]][m[s2]];
}
if(tag){
printf("0\n");
continue;
}
if(!ff1||!ff2){
printf("-1\n");
continue;
}
int d[150];
bool vis[150];
fill(d,d+tot,INF);
fill(vis,vis+tot,false);
d[0]=0;
for(int i=0;i<tot;i++){
int tt,minh=INF;
for(int j=0;j<tot;j++){
if(!vis[j]&&d[j]<minh){
minh=d[j];
tt=j;
}
}
vis[tt]=true;
for(int j=0;j<tot;j++)
d[j]=min(d[j],d[tt]+edge[tt][j]);
}
if(d[1]==INF)
printf("-1\n");
else
printf("%d\n",d[1]);
}
return 0;
}