Spaceship Defence (Small)

Soldiers cross rooms with free jumps between same-color rooms and timed one-way turbolifts, and each query asks for the fastest trip time.

Medium5Shortest pathGraphNo attempts yetTime limit5sMemory limit512 MB

Problem

The enemy has boarded your spaceship, and only better tactics will save it. Your soldiers move around the ship with two devices: teleporters and turbolifts.

A teleporter moves a soldier to another room instantly. Every room holds one teleporter, and every room has a color. A soldier standing in a room can use that room's teleporter to move to any other room of the same color at once. The trip takes 0 seconds.

A turbolift moves soldiers between rooms more slowly. It works like an elevator that runs in many directions. One turbolift carries soldiers from one fixed room to one other fixed room, and the trip takes a fixed amount of time. Turbolifts have two properties.

  • A turbolift runs one way. If a turbolift carries soldiers from room aa to room bb, that same turbolift cannot carry them from room bb to room aa. A separate turbolift may run in that direction.
  • Several soldiers can use the same turbolift, and they do not interfere with each other.

You are given the location and the destination of several soldiers. For each soldier, find the smallest amount of time the trip from the location to the destination can take.

Input

The first line contains the number of test cases TT. TT test cases follow.

The first line of each test case contains the number of rooms in the spaceship, NN. The rooms are numbered from 1 to NN. The next NN lines each contain one string, giving the color of room 1 through room NN in order. Each string uses only the lowercase English letters a to z and the digits 0 to 9, and its length is at most 2.

The next line contains the number of turbolifts, MM. The next MM lines each contain three space separated integers aia_i, bib_i, tit_i, meaning that a turbolift carries soldiers from room aia_i to room bib_i in tit_i seconds.

The next line contains the number of soldiers under your command, SS. The next SS lines each contain the location pjp_j and the destination qjq_j of one soldier, separated by a space.

The limits are as follows.

  • 1T101 \le T \le 10
  • 1N10001 \le N \le 1000
  • 0M30000 \le M \le 3000
  • 1ai,biN1 \le a_i, b_i \le N
  • 0ti10000 \le t_i \le 1000
  • 1S1001 \le S \le 100
  • 1pj,qjN1 \le p_j, q_j \le N

Output

For each test case, first print one line of the form Case #x:, where x is the test case number starting from 1. Then print SS lines, one integer on each. On line jj, print the smallest number of seconds a soldier needs to travel from room pjp_j to room qjq_j. If there is no path from room pjp_j to room qjq_j, print -1.