#P6820. Two Permutations Writing

    ID: 20027 Type: Default 1000ms 256MiB

Two Permutations Writing

Two Permutations Writing

You are given two permutations of the numbers from 1 to n. You will write these two permutations by your left and right hands respectively, from left to right. Writing a number takes 1 unit of time, and both hands can work concurrently as long as they are not writing the same number at the same time.

If both hands are about to write the same number concurrently, one hand must wait for the other to finish writing that number. Determine the minimum time required to finish writing both permutations.

Formal Description
Let A and B be two permutations of {1, 2, ..., n}. Define a function dp(i, j) as the minimal additional time needed to finish writing the remaining parts of the left permutation (starting at index i) and right permutation (starting at index j). Then:

[ \text{dp}(i,j)= \begin{cases} n - j, & \text{if } i = n,\ n - i, & \text{if } j = n,\ 1 + \text{dp}(i+1, j+1), & \text{if } A[i] \neq B[j],\ 1 + \min{ \text{dp}(i+1, j),; \text{dp}(i, j+1) }, & \text{if } A[i] = B[j]. \end{cases} ]

Your task is to compute dp(0, 0), which is the minimum time required to finish writing both permutations.

inputFormat

Input Format:

  • The first line contains an integer n indicating the size of the permutations.
  • The second line contains n space-separated integers representing the first permutation.
  • The third line contains n space-separated integers representing the second permutation.

outputFormat

Output Format:

Print a single integer — the minimum time required to finish writing both permutations.

sample

2
1 2
1 2
3