Taking Stones 2
Time limit2sMemory limit1024 MB
Sum, over all N! removal orders of a colored row of weighted stones, the weights of stones removed while both current neighbors have the opposite color.
- Level
Medium7 of 10
- Topics
- Combinatorics, Math, Dynamic programming, Implementation
- Solved
- No attempts yet
Problem
stones are lined up in a row. Each stone is either white or black.
Number the stones from the left as stone 1, stone 2, ..., stone . The weight of stone is .
You will repeatedly pick one of the lined-up stones and take it, for a total of times, until every stone is gone.
When you take a stone, if that stone is neither the leftmost nor the rightmost among the stones currently lined up, and both stones adjacent to the stone you took have a color different from the stone you took, you gain a score equal to the weight of the stone you took.
There are different ways to take the stones, depending on the order. Find the sum of the scores over all possible ways.
Input
The first line gives a positive integer . ()
The second line gives a string of length consisting only of B and W.
The -th character of is the color of the -th stone from the left. B means the stone is black and W means the stone is white.
The third line gives integers . ()
is the weight of stone .
Output
On the first line, print the sum of the scores over all ways, modulo .
Hint
There are 8 ways that gain a score by taking the second stone from the left, and 8 ways that gain a score by taking the third stone. So the total score is points.