favorite We need a little bit of your help to keep things running, click on this banner to learn more

ADA University - February 3 - Dijkstra

Enterprising Escape

The Enterprise is surrounded by Klingons! Find the escape route that has the quickest exit time, and print that time.

Input is a rectangular grid; each grid square either has the Enterprise or some class of a Klingon warship. Associated with each class of Klingon warship is a time that it takes for the Enterprise to defeat that Klingon. To escape, the Enterprise must defeat each Klingon on some path to the perimeter. Squares are connected by their edges, not by corners (thus, four neighbors).


The first line will contain the number of cases t (2t100). Each case will start with line containing three numbers k, w and h. The value for k (1k25) is the number of different Klingon classes. The value for w (2w1000) is the width of the grid. The value for h (1w1000) is the height of the grid.

Following that will be k lines. Each will consist of a capital letter used to label the class of Klingon ships followed by the duration required to defeat that class of Klingon. The label will not be "E". The duration is in minutes and will be between 0 and 100000 inclusive. Each label will be distinct.

Following that will be h lines. Each will consist of w capital letters (with no spaces between them). There will be exactly one "E" across all h lines, denoting the location of the Enterprise; all other capital letters will be one of the k labels given above, denoting the class of Klingon warship in the square.


Print a single integer - the time required for the Enterprise to escape.

Time limit 4 seconds
Memory limit 128 MiB
Input example #1
6 3 3
A 1
B 2
C 3
D 4
F 5
G 6
2 6 3
A 100
B 1000
Output example #1
Source 2013 North America - Pacific Northwest Region Programming Contest, Problem E