#include <iostream>
#include <fstream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <string>
#include <map>

using namespace std;

int main() {
    freopen ("DATA5.TXT", "r", stdin);
    freopen ("OUT5.TXT", "w", stdout);
    
    int start, end;
    int N;
    map<string, int> ports;
    int dist[40][40];

    for (int set=0;set<5;set++) {
        
    string from, to;
    int cost;
    cin >> N;
    for (int i=0;i<40;i++)
        for (int j=0;j<40;j++)
            dist[i][j]=10000;
            
    for (int i=0;i<N;i++) {
        cin >> from;
        cin >> to;
        cin >> cost;
        
        if (ports.find(from) == ports.end())
           ports[from]=i*2;
        if (ports.find(to) == ports.end())
           ports[to]=i*2+1;
           
        dist[ports[from]][ports[to]] = cost;
        if (from == "YYZ") start=ports[from];
        if (to == "SEA") end=ports[to];
    }

    for (int i=0;i<40;i++)
        for (int j=0;j<40;j++)
            for (int k=0;k<40;k++)
                dist[i][k] = min(dist[i][k], dist[i][j] + dist[j][k]);
    
    cout << dist[start][end] << endl;
    
    }
}

