Privileged Cows
InterviewTime limit1sMemory limit128 MB
Given a sequence of 1s, 2s, and 3s, find the minimum number of arbitrary swaps needed to group all 1s first, then all 2s, then all 3s.
- Level
Medium5 of 10
- Topics
- Greedy, Array, Sorting, Implementation
- Solved
- No attempts yet
Problem
There are cows (). Based on its milk output, each cow is assigned a privilege number of , , or that determines when it gets to drink at the well: a cow with privilege number drinks earliest and one with privilege number drinks latest.
The cows are lined up in some order and must re-arrange themselves so that all the 's are together at the front of the line, the 's follow, and the 's are together at the end.
A single exchange swaps the positions of two cows in the line. Find the minimum number of exchanges needed to order the cows properly.
Input
- Line : a single integer .
- Lines : line contains a single integer, the privilege number of the cow at position in the line.
Output
- Line : a single integer, the minimum number of exchanges required to order the cows properly.
Hint
Here is one way to sort them (a < marks a position taking part in the exchange):
2 2 2< 1 1
2< 1 1 1 1
1< 2 2 2 2
3 3< 2 2 2
3 3 3 3< 2
3 3 3 3 3
2 2< 3 3 3
3 3 3 3 3
1 1 1< 2< 3