This page is still under construction.

Parts of this page are still being built. What you see may change.

Luna Likes Love

Interview

Time limit2sMemory limit512 MB

Summary
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 2n2n friends into a long line and gave each of them an integer between 11 and nn, 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 nn 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 nn.

The second line contains 2n2n space-separated integers a_ia\_i (1≤a_i≤n1 \le a\_i \le n), 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.

Examples2

  1. Example 1

    Input
    3
    3 1 2 1 2 3
    
    Expected output
    4
    
  2. Example 2

    Input
    5
    5 1 2 3 2 3 1 4 5 4
    
    Expected output
    7