/*
* 解題總結 :
* 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 s, e;
}ds[MAXN];
struct E{
int to, w, nxt;
}edge[MAXM];
queue<int> q;
int tot, head[MAXN], dis[MAXN], inqtot[MAXN], n;
bool inq[MAXN];
inline void clear(){
while(!q.empty()) q.pop();
tot = 0;
memset(head, -1, sizeof head);
memset(dis, INF, sizeof dis);
dis[1] = 0;
memset(inqtot, 0, sizeof inqtot);
memset(inq, false, sizeof inq);
}
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 bool SPFA(){
q.push(1);
inq[1] = true;
++inqtot[1];
while(!q.empty()){
int id = q.front();
q.pop();
inq[id] = false;
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;
if(!inq[to]){
inq[to] = true;
++inqtot[to];
q.push(to);
if(inqtot[to] > n) return false;
}
}
}
}
return true;
}
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);
bool ok = SPFA();
if(!ok) continue;
if(dis[n] == INF) cout << -1 << endl;
else cout << dis[n] << endl;
}
return 0;
}