#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

using namespace std;

int n, f, start, finish;
string cities[30];
int dist[30][30];
char p;

int Find(string a)
{
    for (int i = 0; i < 30; i++){
        if (cities[i] == a)
            return i;
    }
    return -1;
}

void enterdata()
{
    string a, b;
    cin >> a >> b;

    if ( Find(a) == -1 )
        cities[f++] = a;
    if ( Find(b) == -1 )
        cities[f++] = b;
    if (a == "YYZ")
        start = Find(a);
    else if (a == "SEA")
        finish = Find(a);

    if (b == "YYZ")
        start = Find(b);
    else if (b == "SEA")
        finish = Find(b);

    cin >> dist[ Find(a) ][ Find(b) ];

}

void input()
{
    for (int i = 0; i < 30; i++){
        for (int j = 0; j < 30; j++){
            dist[i][j] = -1;
            cities[i] = "";
        }
    }
    cin >> n;
    for (int i = 0; i < n; i++){
        enterdata();
    }
}

void floyd()
{
    for (int k = 0; k < 30; k++){
        for (int i = 0; i < 30; i++){
            for (int j = 0; j < 30; j++){
                if ( dist[i][k] != -1 && dist[k][j] != -1 ){
                    dist[i][j] = min( dist[i][j], dist[i][k]+dist[k][j] );
                }
            }
        }
    }
}


main()
{
    freopen("DATA5.txt", "r", stdin);
    freopen("OUT5.txt", "w", stdout);

    for (int x = 0; x < 5; x++){
        f = 1;
        start = 0; finish = 0;

        input();
        floyd();

        cout << dist[start][finish] << endl;
    }
    return 0;
}









