Winning the Vote
Time limit2sMemory limit512 MB
Given a vote order where 0 marks a teller, find the fewest adjacent swaps of a teller with a voter so party 1 wins, or report impossible.
- Level
Medium6 of 10
- Topics
- Dynamic programming, Implementation
- Solved
- No attempts yet
Problem
In the country of Elecuador, a very strange voting system is used. When it is time for the election, each of the citizens arrives at the voting station in some order. There are only two parties to vote for, named and . When a citizen arrives, they vote for one of the parties, unless they are a teller. A teller does not vote. Instead, the teller counts how many votes each party has at the time the teller arrives. If one party has more votes than the other, that party receives one point. If the two parties have the same number of votes, neither receives a point. The party with the most points at the end wins. If both parties end up with the same number of points, chaos ensues.
As the president of Elecuador representing party , you are worried that the coming election will end your reign. You have a plan. You know how everyone in the country will vote, who the tellers are, and the order in which everyone arrives. By making the right phone calls, you can also change when the tellers arrive. In one move, you can swap a teller with an adjacent person in the list of arrivals. Two adjacent non-tellers cannot be swapped.
What is the minimum number of swaps needed to ensure that party wins?
Input
The first line contains an integer (), the number of citizens in Elecuador. The second line contains a string of length , consisting of the characters , , and . The string gives the order in which the citizens arrive at the voting station. If is or , the -th citizen votes for party or party , respectively. If is , the -th citizen is a teller.
Output
If party can ensure victory, output one integer: the minimum number of swaps needed. Otherwise, output impossible.