Bilbo's Birthday

Time limit3sMemory limit256 MB

Summary
Given two permutations of the same N names, find an ordering of the names that minimizes the total number of pairs ordered differently from Frodo's chart plus pairs ordered differently from Sam's chart.
Level

Medium7 of 10

Topics
Sorting, Divide and conquer, Combinatorics, Greedy
Solved
No attempts yet

Problem

Frodo and Sam are planning Bilbo's upcoming 111th birthday party. They have invited every hobbit in Middle-earth, and without a single exception all of them will attend. The hobbits will sit in one row along a very long dinner table.

Frodo and Sam prepared their seating charts separately, without consulting each other, so each of them produced one chart. Now they want to combine the two charts into a single final seating chart.

For any two hobbits xx and yy, whether xx sits before or after yy in a given chart is called their relative order in that chart. If the relative order in the final chart differs from the order in Frodo's chart, count one mismatch; if it differs from the order in Sam's chart, count another. In other words, for every pair of hobbits, compare the final chart against Frodo's chart and against Sam's chart and add up the number of charts in which their order differs.

Choose the final chart so that this total number of mismatches is as small as possible. Write a program that computes this minimum.

Input

The input consists of several test cases. The first line of each test case contains an integer NN (1≤N≤100 0001 \le N \le 100\,000), the number of hobbits. The next two lines are Frodo's seating chart and Sam's seating chart, respectively; each line lists NN distinct names separated by single spaces. Every name consists only of alphabetic characters and is at most 66 characters long. The set of names appearing in the two charts is identical. The last line of the input contains 00 and must not be processed.

Output

For each test case, print the minimum number of mismatches on its own line.

Examples1

  1. Example 1

    Input
    3
    Frodo Sam Bilbo
    Sam Frodo Bilbo
    5
    A B C D E
    B A D E C
    0
    
    Expected output
    1
    3