#include <iostream>
#include <stdio.h>
#include <string.h>
#define INF 1000 + 10
#define maxn 100000
using namespace std;
int n;
struct node
{
char first[5];
char last[5];
int time;
} arr[INF];
int map[INF][INF];
int dis[INF];
int vis[INF];
void dijkstra()
{
int pos = 1;
for( int i = 1; i <= n; i++)
{
vis[i] = false;
dis[i] = map[1][i];
}
dis[1] = 0;
vis[1] = true;
dis[1] = 0;
for( int i = 1; i < n; i++)
{
int min = maxn;
for( int i = 1; i<=n; i++)
{
if( !vis[i] && dis[i] < min )
{
min = dis[i];
pos = i;
}
}
vis[pos] = true;
for( int i = 1; i<= n; i++)
if( !vis[i] && map[pos][i] < maxn && dis[i] > dis[pos] + map[pos][i] )
dis[i] = dis[pos] + map[pos][i];
}
}
}
int main()
{
har str[100];
int i ,j,len;
while(scanf("%d",&n),n)
{
// memset(map,maxn,szieof(map)); 这样是不对的
/*例如 memset(a,1,20) 就是对a指向的内存的20个字节进行赋值,每个都用ASCII为1的字符去填充,转为二进制后,1就是00000001,占一个字节。一个INT元素是4字节,合一起就是1000000010000000100000001,就等于16843009,就完成了对一个INT元素的赋值了。*/
for( i =1; i<= n; i++)
{
scanf("%d %s",&arr[i].time, str);
len = strlen(str);
for( j =0; j<4; j++)
{
arr[i].first[j] = str[j];
arr[i].last[j] = str[len - 4 + j];
}
arr[i].first[4] = arr[i].last[4] = '\0';
}
for( i = 1; i <= n; i++)
{
for( j = 1; j <= n; j++)
{
map[i][j] = maxn;
if( i == j)
continue;
if( strcmp(arr[i].last, arr[j].first) == 0)
map[i][j] = arr[i].time;
}
}
dijkstra();
if(dis[n] != maxn)
cout<<dis[n]<<endl;
else
cout<<"-1"<<endl;
}
}