Opening the Treasure Box
Time limit1sMemory limit256 MB
For each start position, find the minimum replacement cost plus walking cost (c per step) to make the letter string a palindrome.
- Level
Hard8 of 10
- Topics
- Dynamic programming, String, Prefix sum
- Solved
- No attempts yet
Problem
Apeach set out on a journey to find a legendary treasure. After breaking through several gates, he found a box that is presumed to hold the treasure. The box was locked, and an inscription on it read: "To open the box, change the letters below it so that they read the same forwards and backwards."

Near the box, Apeach found several stone tablets lined up in a row beneath it, each with a letter written on it. Many more letter tablets were scattered around the box. It seems the box opens when the tablets in the row are replaced so that they form a palindrome (a word, number, or sentence that reads the same forwards and backwards). Apeach has little stamina, so he wants to get the treasure while spending as little as possible. Replacing each tablet costs a different amount of stamina. Moving one position costs stamina. That is, if the previous position was tablet and he now replaces tablet , the move costs stamina. For each of the tablets, find the minimum stamina needed to get the treasure when starting from that tablet's position.
Input
The first line contains the number of test cases ().
Each test case is given in the following format.
The first line contains the number of tablets () and the stamina spent to move one position ().
The second line contains a string of length . The -th character is the letter written on the -th tablet. Each character is an uppercase English letter.
The third line contains integers. The -th integer is the stamina spent to replace the -th tablet. Each value is between 1 and , inclusive.
The sum of over all test cases does not exceed 1,000,000.
Output
For each test case, print on one line the minimum stamina Apeach must spend when starting from the position of each tablet, separated by spaces.