/*
* 解題總結 :
* 1 : 首先明確strlen, size這些函數都時O(N)的,再套兩個for,妥妥的T。
* 2 : 因爲只要用到前面的四個字符和最後的四個字符,所以先可以預處理出這些數據。
* 3 : 如果使用鏈式前向星建圖,注意edge結構體數組要開MAXN^2,RE了好幾發。
*/
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e3 + 10;
const int MAXM = 1e6 + 10;
const int INF = 0x3f3f3f3f;
struct input{
int w;
string e, s;
}ds[MAXN];
struct E{
int to, w, nxt;
}edge[MAXM];
int tot, n, head[MAXM], dis[MAXN];
priority_queue<pair<int, int>> q;
bool use[MAXN];
inline void clear(){
tot = 0;
memset(head, -1, sizeof head);
memset(dis, INF, sizeof dis);
dis[1] = 0;
while(!q.empty()) q.pop();
memset(use, false, sizeof use);
}
inline void addedge(int u, int v, int w){
edge[tot].to = v;
edge[tot].w = w;
edge[tot].nxt = head[u];
head[u] = tot++;
}
inline void dijkstra(){
q.push({0, 1});
while(!q.empty()){
auto it = q.top();
q.pop();
int id = it.second;
if(use[id]) continue;
use[id] = true;
for(int i = head[id]; ~i; i = edge[i].nxt){
int to = edge[i].to;
int w = edge[i].w;
if(dis[id] + w < dis[to]){
dis[to] = dis[id] + w;
q.push({-dis[to], to});
}
}
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
//cout << setiosflags(ios::fixed) << setprecision(1); //保留小數點後1位
//cout << setprecision(1); //保留1位有效數字
// freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
while(cin >> n, n){
clear();
for(int i = 1; i <= n; ++i){
string ss;
cin >> ds[i].w >> ss;
ds[i].s = ss.substr(0, 4);
ds[i].e = ss.substr(ss.size() - 4, 4);
}
for(int i = 1; i <= n; ++i)
for(int j = 1; j <= n; ++j)
if(i != j && ds[i].e == ds[j].s) addedge(i, j, ds[i].w);
dijkstra();
if(dis[n] == INF) cout << -1 << endl;
else cout << dis[n] << endl;
}
return 0;
}