#include<iostream> #include<cstring> #include<cstdio> #include<cmath> #include<algorithm> #include<cstdlib> #include<map> #include<queue> #include <deque> #include <list> #include <ctime> #include <stack> #include <vector> #include<set> #define Maxn 155 #define MOD typedef long long ll; #define FOR(i,j,n) for(int i=j;i<=n;i++) #define DFR(i,j,k) for(int i=j;i>=k;--i) #define lowbit(a) a&-a #define Max(a,b) a>b?a:b #define Min(a,b) a>b?b:a const int inf = 0xfffffff; const double pi = acos(-1.0); using namespace std; int n,t; int map_s[Maxn][Maxn]; int visit[Maxn],dis[Maxn]; int Dijkstra(int s,int n) { int i,j; FOR(i,1,n) dis[i]=map_s[s][i],visit[i]=false; dis[1]=0; visit[1]=true; FOR(i,1,n) { int k,minn=inf; FOR(j,1,n) if(!visit[j]&&dis[j]<minn) minn=dis[k=j]; if(minn==inf) break; visit[k]=true; FOR(j,1,n) if(!visit[j]&&dis[j]>dis[k]+map_s[k][j]) dis[j]=dis[k]+map_s[k][j]; } return dis[2]; } int main() { bool flag=false; map<string,int> mp; char start[33],endd[33]; while(~scanf("%d",&n)&&n!=-1) { mp.clear(); flag=false; FOR(i,1,Maxn) FOR(j,1,Maxn) map_s[i][j]=inf; scanf("%s%s",start,endd); mp[start]=1; mp[endd]=2; int counter=3; if(strcmp(start,endd)==0) flag=true; FOR(i,1,n) { scanf("%s%s%d",start,endd,&t); if(!mp[start]) mp[start]=counter++; if(!mp[endd]) mp[endd]=counter++; map_s[mp[start]][mp[endd]]=map_s[mp[endd]][mp[start]]=t; } if(flag) {printf("0\n");continue;} Dijkstra(1,counter); printf("%d\n",dis[2]==inf?-1:dis[2]); } return 0; }