All problems

Problem 648

Minimum Swaps To Make Sequences Increasing

Hard · 30 pts · Dynamic Programming

Problem

You are given two arrays A and B of the same length N. In one operation you may swap A[i] with B[i] for some index i. Find the minimum number of operations that makes both arrays strictly increasing. The input always allows this. Scan from left to right keeping two values: the fewest swaps so far if position i is not swapped, and if it is swapped. Whether i may keep or flip the choice made at i - 1 depends only on comparing the four values at i - 1 and i.

Input

The first line contains N. The second line contains A. The third line contains B.

Output

Print the minimum number of swaps.

Constraints

2 <= N <= 100000; 0 <= A[i], B[i] <= 200000; a solution always exists

Example input

4
1 3 5 4
1 2 3 7

Example output

1

Explanation

With A = 1 3 5 4 and B = 1 2 3 7, swapping the last pair gives A = 1 3 5 7 and B = 1 2 3 4, both strictly increasing. One swap is enough, so the answer is 1.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Max Dot Product of Two Subsequences Next: Largest Divisible Subset