Son of Durin
Time limit2sMemory limit512 MB
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 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 sitedthe cell where Thorin starts. Exactly one cell of the map holds it0through9andAthroughFa cave. Read the character as a hexadecimal digit to get the cave number. Numbering starts at 0, so0,3, andBare 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 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 units of time while teleporting at most times.
Input
The first line contains the number of test cases ().
The first line of each test case contains four space separated integers , , , and (, , ). is the number of rows of the map, is the number of columns, is the limit on teleports, and is the limit on time.
Each of the next lines contains characters and gives one row of the map.
The last line contains the coin counts of the caves in order, starting with cave 0, separated by spaces. Each count is between 0 and . The cave numbers that appear on the map are exactly 0 through , and no number appears twice ().
Output
For each test case print the largest number of coins Thorin can collect, one per line.