Bribing the Prisoners
InterviewTime limit2sMemory limit512 MB
Release Q prisoners from a row of P cells in the order that minimizes bribes paid to neighbors reached by the news. Find that minimum total cost.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Intervals, Divide and conquer
- Solved
- No attempts yet
Problem
A prison has cells in one row, numbered from the left. Every cell is a solitary cell and holds exactly one prisoner. Neighboring cells share a window, so a prisoner can talk to the prisoner next door.
When you release the prisoner of some cell, the prisoner in each cell right next to it learns about it and starts a riot. Releasing one prisoner therefore costs one gold coin for the prisoner in each of the two neighboring cells. The news keeps traveling sideways from window to window, so you have to pay every prisoner the news reaches. An empty cell has no prisoner to pass the news along, so the news stops there.
Today you release the prisoners held in cells . The number of coins depends on the order of the releases. Find the order that spends the fewest coins and report how many coins that order needs.
Input
The first line contains two integers and separated by a space. (, , )
The second line contains integers separated by spaces. Each value is the cell number of a prisoner to release, and no value is given twice. ()
Output
Print on one line the minimum number of gold coins needed to release all prisoners.