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.
Hard8GreedyString matchingPrefix sumNo attempts yetTime limit2sMemory limit32 MBMinhyuk is looking at the 2N stones lying along the shore of a lake when a thought strikes him. There are N white stones and N 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 0).
The stones are very heavy, so carrying a stone a distance of x costs x 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.
The first line contains the circumference of the lake R and the number of black stones N. Each of the next 2N lines contains the position Pk of one stone and its colour Ck. A Ck of B means a white stone, and a Ck 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 Pk. (1≤N≤200000, 2N≤R≤109, 0≤Pk<R)
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.
You may assume that a stone has size 0, 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.