Spaceship Defence (Large)

Soldiers teleport free between same-color rooms and ride directed timed turbolifts; each query asks the fastest time from its start room to its destination.

Medium7Shortest pathGraphNo attempts yetTime limit5sMemory limit512 MB

Problem

The enemy has boarded your spaceship. Your soldiers move around the ship with two devices, teleporters and turbolifts.

Every room holds one teleporter, and every room has one color. A soldier standing in a room uses that room's teleporter to move instantly to any other room of the same color. This move costs no time.

A turbolift carries soldiers from one room to one other room, and the trip takes a fixed amount of time. A turbolift runs in one direction only. A turbolift that carries soldiers from room aa to room bb cannot carry them from room bb to room aa, though a separate turbolift may do that. Several soldiers can use the same turbolift at once, and they do not interfere with each other.

You are given the starting room and the destination room of several soldiers. For each soldier, find the smallest amount of time the trip from the starting room to the destination room 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 an integer NN, the number of rooms. Rooms are numbered from 1 to NN. The next NN lines each contain one string, the color of room 1 through room NN in order. Each color is a string of length 1 or 2 that uses only the lowercase letters a to z and the digits 0 to 9.

The next line contains an integer MM, the number of turbolifts. Each of the next MM lines contains 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 an integer SS, the number of soldiers. Each of the next SS lines contains two integers pjp_j and qjq_j, the starting room and the destination room of one soldier.

Constraints

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

Output

For each test case, first print one line holding Case #x:, where xx is the test case number starting from 1. Then print SS lines. Line jj holds the smallest number of seconds a soldier needs to travel from room pjp_j to room qjq_j, as an integer. If no such trip exists, print -1.