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 MBThe 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.
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.
The first line contains the number of test cases T. T test cases follow.
The first line of each test case contains the number of rooms in the spaceship, N. The rooms are numbered from 1 to N. The next N lines each contain one string, giving the color of room 1 through room N 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, M. The next M lines each contain three space separated integers ai, bi, ti, meaning that a turbolift carries soldiers from room ai to room bi in ti seconds.
The next line contains the number of soldiers under your command, S. The next S lines each contain the location pj and the destination qj of one soldier, separated by a space.
The limits are as follows.
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 S lines, one integer on each. On line j, print the smallest number of seconds a soldier needs to travel from room pj to room qj. If there is no path from room pj to room qj, print -1.