Wedding Train
Time limit1sMemory limit128 MB
Arrange N guests in a line minimizing total adjacent height difference while keeping K given family members in a fixed relative order.
- Level
Hard8 of 10
- Topics
- Dynamic programming, Greedy, Sorting
- Solved
- No attempts yet
Problem
Slavko is organizing a wedding for his friend Mirko.
The highlight of the wedding is a popular group dance called the "Train". All guests line up one behind another, and everyone except the first person places their hands on the shoulders of the person directly in front of them; then the whole line dances cheerfully through the hall.
Slavko wants the train to look nice. If two neighbouring people differ greatly in height, the train does not look nice, so he measures the train's ugliness as the sum, over every pair of neighbours, of the absolute difference of their heights.
Mirko's family is very conservative: nowhere in the train may a younger member of the family stand in front of an older member. In other words, the family members must appear along the train from the oldest to the youngest (they need not be adjacent). All other guests may stand anywhere.
Given the heights of all guests and the age order of Mirko's family, arrange everyone into a single train so that the family's age order is respected and the total ugliness (the sum of absolute height differences between neighbours) is as small as possible.
Input
The first line contains two integers and separated by a space (, , ): the total number of guests and the number of members of Mirko's family.
Each of the next lines contains one integer (), the height of a guest. Guests are numbered from to , and the first guests are Mirko's family listed from oldest to youngest (guest is the oldest family member and guest is the youngest). Therefore, in the train, for every with , family guest must appear somewhere before family guest .
Output
Output a single integer: the minimum possible total ugliness, that is, the smallest achievable sum of absolute height differences between neighbouring guests over all valid trains.