Bilbo's Birthday
Time limit3sMemory limit256 MB
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 and , whether sits before or after 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 (), the number of hobbits. The next two lines are Frodo's seating chart and Sam's seating chart, respectively; each line lists distinct names separated by single spaces. Every name consists only of alphabetic characters and is at most characters long. The set of names appearing in the two charts is identical. The last line of the input contains and must not be processed.
Output
For each test case, print the minimum number of mismatches on its own line.