Luna Likes Love
InterviewTime limit2sMemory limit512 MB
Given 2n friends in a line where each of n labels appears twice, repeatedly swap adjacent friends or remove an adjacent matching pair, and find the minimum number of actions to remove all pairs.
- Level
Medium7 of 10
- Topics
- Greedy, Stack, Array, Implementation
- Solved
- No attempts yet
Problem
Luna came up with a wild idea. She lined up her friends into a long line and gave each of them an integer between and , inclusive. Each number is used exactly twice. Each pair of friends who share the same number forms a couple.
Luna wants to send each of the couples on a date. That is not so straightforward, though. To send a couple on a date, the two friends forming the couple must stand next to each other in the line, meaning nobody else stands between them. Luna can take two actions:
- She can swap any two friends who stand next to each other in the line.
- If a couple stands next to each other in the line, she can send them on a date. This removes the couple from the line, and the remaining friends shift to fill the gap.
She can perform the actions in any order. For example, she can make some swaps, send some couples on dates, and then go back to making swaps.
Find and report the minimum number of actions needed to send everybody on a date.
Input
The first line contains a single integer .
The second line contains space-separated integers (), the numbers the friends in the line received, in order.
Output
Print a single line with the minimum number of actions Luna must make to send every couple on a date.
Hint
In the first sample, Luna can start by swapping the third and the fourth friend. After this swap the line looks as follows: 3 1 1 2 2 3.
Then she can send the couple with number 1 and the couple with number 2 on a date, in any order. Once she does, the two friends with number 3 are adjacent in line, and Luna can send them on a date too.
This solution takes 4 actions in total: one swap and three dates.