// 题意 : 一个人要去旅行 给你起点和终点 求最少花费 其中花费为经过路径的总费用减去该路径的中的最大花费段
// 直接搜索 稍微加了个剪枝 主要是数据规模小
#include <iostream>
#include <map>
#include <algorithm>
#include <queue>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <vector>
using namespace std;
#define MOD 1000000007
#define maxn
map<string,int> mp;
vector <int >V[110];
bool visit[110];
int rc[110][110];
char str1[20],str2[20];
char ss[20],ts[20];
int s,t;
int ans;
void dfs(int u,int sum,int mx){
// if(u==t) return;
visit[u]=true;
if(sum-mx>ans) return; // 加了个小剪枝
int i,v,ts,tm;
int len=V[u].size();
for(i=0;i<len;i++){
v=V[u][i];
if(!visit[v]){
ts=sum+rc[u][v];
tm=max(mx,rc[u][v]);
if(v==t){
ans=min(ans,ts-tm);
return ;
}
dfs(v,ts,tm);
visit[v]=false;
}
}
}
int main(){
int m;
int n;
while(scanf("%s %s",ss,ts)!=EOF){
scanf("%d",&m);
int i,val;
int u,v;
n=1;
map<string,int>::iterator it;
for(i=0;i<m;i++){
scanf("%s %s %d",str1,str2,&val);
it=mp.find(str1);
if(it!=mp.end()){
u= mp[str1];
}
else{
u=n++;
mp[str1]=u;
}
it=mp.find(str2);
if(it!=mp.end()){
v= mp[str2];
}
else{
v=n++;
mp[str2]=v;
}
V[u].push_back(v);
rc[u][v]=val;
}
s=mp[ss];
t=mp[ts];
memset(visit,0,sizeof(visit));
ans=MOD;
//printf("%d %d
",s,t);
dfs(s,0,0);
printf("%d
",ans);
mp.clear();
for(i=1;i<n;i++)
V[i].clear();
}
}