//这道题要用map来储存输入的地点信息,本质还是一题最短路径!
#include <iostream>
#include <stdio.h>
#include <cmath>
#include <map>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
#define MAXN 200
#define INF 0x3f3f3f3f
map<string,int>Map;
int visit[MAXN];
int Edge[MAXN][MAXN];
int dist[MAXN];
void Dijkstra(int v,int n)
{
for(int i=1; i<=n; i++)
{
visit[i] = 0;
dist[i] = Edge[v][i];
}
visit[v] = 1;
for(int i=1; i<=n; i++)
{
int MIN = INF;
int u = v;
for(int j=1; j<=n; j++)
{
if(!visit[j]&&dist[j]<MIN)
{
u = j;
MIN = dist[j];
}
}
visit[u] = 1;
for(int k=1; k<=n; k++)
{
if(dist[u]+Edge[u][k]<dist[k])
dist[k] = dist[u]+Edge[u][k];
}
}
}
int main()
{
int n,m,w,k;
string st,en,u,v;
while(~scanf("%d",&m))
{
if(m==-1)
break;
Map.clear();
k=1;
for(int i=1; i<MAXN; i++)
for(int j=1; j<MAXN; j++)
{
if(i==j)
Edge[i][j] = 0;
else
Edge[i][j] = INF;
}
cin>>st>>en;
if(!Map[st])
Map[st] = k++;
if(!Map[en])
Map[en] = k++;
for(int i=1; i<=m; i++)
{
cin>>u>>v>>w;
if(!Map[u])
Map[u] = k++;
if(!Map[v])
Map[v] = k++;
//printf("%d %d\n",Map[u],Map[v]);
if(w<Edge[Map[u]][Map[v]])
Edge[Map[v]][Map[u]] = Edge[Map[u]][Map[v]] = w;
}
//cout<<k<<" "<<Map[st]<<" "<<Map[en]<<endl;
Dijkstra(Map[st],k-1);
if(dist[Map[en]] == INF)
printf("-1\n");
else
printf("%d\n",dist[Map[en]]);
}
return 0;
}