Under construction

Still being built. Things may change

Son of Durin

Time limit2sMemory limit512 MB

Summary
Given a grid with walls, teleport pads, and up to 15 coin caves, find the most gold collectible within L moves and P teleports.
Level

Hard8 of 10

Topics
BFS, Dynamic programming, Shortest path, Bit manipulation
Solved
No attempts yet

Problem

Thorin wants to collect as many gold coins as he can before winter arrives. He has a map of the tunnels inside the mountain. The map marks the caves that hold gold coins, and it also records how many coins each cave holds.

The map is an N×MN \times M grid. Each cell holds one of these characters.

  • . an empty cell Thorin can walk on
  • # a wall. Thorin cannot enter it and cannot cross it
  • ^ a teleport site
  • d the cell where Thorin starts. Exactly one cell of the map holds it
  • 0 through 9 and A through F a cave. Read the character as a hexadecimal digit to get the cave number. Numbering starts at 0, so 0, 3, and B are caves 0, 3, and 11

In one unit of time Thorin moves to one of the four cells adjacent up, down, left, or right, as long as that cell is not a wall. While he stands on a ^ cell he can spend one unit of time to teleport to any other ^ cell of the map. He can also walk off a ^ cell to an adjacent cell in the usual way. He can teleport at most PP times in total.

The moment Thorin enters a cave he takes all of its coins. Taking the coins costs no time. Entering a cave he has already emptied gives him nothing more. He may pass through the same cell any number of times.

Compute the largest number of coins Thorin can collect within LL units of time while teleporting at most PP times.

Input

The first line contains the number of test cases TT (1≤T≤101 \le T \le 10).

The first line of each test case contains four space separated integers NN, MM, PP, and LL (1≤N,M≤5001 \le N, M \le 500, 0≤P≤1050 \le P \le 10^5, 0≤L≤1090 \le L \le 10^9). NN is the number of rows of the map, MM is the number of columns, PP is the limit on teleports, and LL is the limit on time.

Each of the next NN lines contains MM characters and gives one row of the map.

The last line contains the coin counts of the KK caves in order, starting with cave 0, separated by spaces. Each count is between 0 and 10910^9. The cave numbers that appear on the map are exactly 0 through K−1K-1, and no number appears twice (1≤K≤151 \le K \le 15).

Output

For each test case print the largest number of coins Thorin can collect, one per line.

Examples2

  1. Example 1

    Input
    1
    6 4 1 15
    #d.^
    ##..
    ....
    0...
    ####
    1.^.
    100 1000
    
    Expected output
    1100
    
  2. Example 2

    Input
    1
    5 5 0 20
    d....
    .###.
    .#0#.
    .#.#.
    1...2
    5 7 9
    
    Expected output
    21