// Arup Guha
// 8/30/2017
// Solution to 2017 UCF Locals Problem: Multimodal Transport

import java.util.*;

public class transport {

	public static int v;
	public static ArrayList[] graph;
	public static HashMap<String,Integer> cityMap;
	public static HashMap<String,Integer> modeMap;

	public static void main(String[] args) {

		// Same for all cases.
		modeMap = new HashMap<String,Integer>();
		modeMap.put("AIR", 0);
		modeMap.put("SEA", 1);
		modeMap.put("RAIL", 2);
		modeMap.put("TRUCK", 3);

		Scanner stdin = new Scanner(System.in);
		int numCases = stdin.nextInt();

		// Process each case.
		for (int loop=0; loop<numCases; loop++) {

			// Set everything up.
			v = stdin.nextInt();
			graph = new ArrayList[4*v];
			for (int i=0; i<4*v; i++) graph[i] = new ArrayList<edge>();
			cityMap = new HashMap<String,Integer>();

			// Read in cities.
			for (int i=0; i<v; i++) {
				String city = stdin.next();
				int extra = stdin.nextInt();
				cityMap.put(city, 4*i);

				// Add in edges for switching cost.
				for (int j=0; j<4; j++) {
					for (int k=1; k<4; k++) {
						graph[4*i+j].add(new edge(4*i+k,extra));
						graph[4*i+k].add(new edge(4*i+j,extra));
					}
				}
			}

			// Add in all of the edges between cities.
			int e = stdin.nextInt();
			for (int i=0; i<e; i++) {
				int v1 = cityMap.get(stdin.next());
				int v2 = cityMap.get(stdin.next());
				int add = modeMap.get(stdin.next());
				int w = stdin.nextInt();
				v1 += add;
				v2 += add;
				graph[v1].add(new edge(v2,w));
				graph[v2].add(new edge(v1,w));
			}

			// Get query and solve it.
			int start = cityMap.get(stdin.next());
			int end = cityMap.get(stdin.next());
			System.out.println(modDij(start, end));
		}
	}

	public static int modDij(int s, int e) {

		// Set up Dijkstras.
		edge[] dist = new edge[4*v];
		for (int i=0; i<dist.length; i++) dist[i] = new edge(i, 1000000000);
		for (int i=0; i<4; i++) dist[s+i] = new edge(s+i,0);

		// Add to pq.
		PriorityQueue<edge> pq = new PriorityQueue<edge>();
		for (int i=0; i<dist.length; i++) pq.offer(dist[i]);

		// Run Dijkstra's.
		while (pq.size() > 0) {

			// Get next estimate.
			edge cur = pq.poll();

			// We made it!
			if (cur.to/4 == e/4) return cur.w;

			// Try going places from here.
			for (edge next : (ArrayList<edge>)(graph[cur.to])) {
				int neww = cur.w + next.w;

				// This edge gives us a better estimate!
				if (neww < dist[next.to].w) {
					pq.remove(dist[next.to]);
					dist[next.to].w = neww;
					pq.offer(dist[next.to]);
				}
			}
		}

		// Should never get here.
		return -1;
	}
}

class edge implements Comparable<edge> {

	public int to;
	public int w;

	public edge(int dest, int myw) {
		to = dest;
		w = myw;
	}

	public int compareTo(edge other) {
		return this.w - other.w;
	}
}