Table Tennis Team Lineup
Time limit1sMemory limit64 MB
Reorder the queue with the fewest take-and-reinsert moves so each consecutive block of K holds the next K weakest players.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Sorting, Binary search
- Solved
- No attempts yet
Problem
The annual table tennis team competition for students of the University of Zagreb takes place next Saturday. Each team consists of students, and students are waiting in a queue to register.
Krešo works at the registration desk. He does not feel like doing his job, so he decided that students may not pick their own team. The first students in the queue form the first team, the next students form the second team, the next students form the third team, and so on. is divisible by , so no student is left without a team.
Ante has rated the skill of every student with one integer. He wants the weakest students in the first team, the next weakest in the second team, the next weakest in the third team, and so on, so the teams get stronger from the front of the queue to the back. Students who end up in the same team may stand in any order among themselves.
Krešo has just gone on a break, so Ante decided to shuffle the queue himself. Ante can tell one student to step out of the queue and stand back in it behind another student, or to go to the front of the queue. Moving one student this way takes him one minute.
Krešo may come back at any moment, so Ante needs to reach his goal as fast as possible. Determine the minimum number of minutes Ante needs.
Input
The first line contains the integers and . () is divisible by .
The second line contains space separated integers . () The value is the skill of the -th student in the queue.
All students have distinct skills.
Output
Print the minimum number of minutes on the first and only line.
Hint
In the sample with six students and equal to 3, Ante moves the students with skills 5, 6 and 3 to the front of the queue. That takes him three minutes.