Swapping the Stones
Time limit2sMemory limit32 MB
Move stones along empty arcs of a circular shore so black and white stones exchange position sets with minimum total carry distance, or report impossibility.
- Level
Hard8 of 10
- Topics
- Greedy, String matching, Prefix sum
- Solved
- No attempts yet
Problem
Minhyuk is looking at the stones lying along the shore of a lake when a thought strikes him. There are white stones and black stones, so what if he swapped the positions of the white stones and the black stones?
Minhyuk has nothing better to do, so he decides to really rearrange the colours. He owns no paint or any tool like it, so he has to lift the stones one at a time and carry them.
Before he starts, he walks once around the lake and measures the circumference and the position of every stone, both taken from the point where he started (position ).
The stones are very heavy, so carrying a stone a distance of costs force. Another stone in the way is a nuisance, so the stretch of shore he carries a stone across must contain no other stone.
Minhyuk does not want to spend force on a pointless job. Find the smallest force he needs to swap the positions of the black stones and the white stones.
Input
The first line contains the circumference of the lake and the number of black stones . Each of the next lines contains the position of one stone and its colour . A of B means a white stone, and a of W means a black stone. The number of black stones equals the number of white stones, and the stones are given in increasing order of . (, , )
Output
If Minhyuk cannot swap the positions of the black stones and the white stones, print -1. Otherwise print the smallest force he needs. The answer can be very large.
Hint
You may assume that a stone has size , and the point where Minhyuk puts a stone down does not have to be an integer. After all the stones have been moved, they must sit at the same positions as before with only their colours exchanged.