PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#FT0000080. Chèn tối ưu (Optimal Insertion)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Chèn tối ưu (Optimal Insertion)

Optimal Insertion

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

You are given two integer sequences a1,a2,…,ana_1,a_2,\ldots,a_n and b1,b2,…,bmb_1,b_2,\ldots,b_m. Insert all elements of bb at arbitrary positions in aa to form a sequence cc of length n+mn+m.

The relative order of the elements originally in aa must remain unchanged. The elements from bb, however, may appear in any order. You may insert them before the first element of aa, after its last element, or between consecutive elements; several elements may share an insertion gap.

An inversion is a pair of indices (i,j)(i,j) satisfying i<ji<j and ci>cjc_i>c_j. Equal elements never form an inversion. Determine the minimum possible number of inversions among all valid merged sequences.

Input

The first line contains integers n,mn,m, the lengths of the sequences.

The second line contains exactly nn integers a1,a2,…,ana_1,a_2,\ldots,a_n in their original order.

The third line contains exactly mm integers b1,b2,…,bmb_1,b_2,\ldots,b_m. Their input order need not be preserved during insertion.

Output

Print one integer: the minimum number of inversions in the resulting sequence.

Subtasks

  • Subtask 1 (20 points): 1≤n,m≤81\le n,m\le 8; 1≤ai,bj≤1091\le a_i,b_j\le 10^9 for all 1≤i≤n1\le i\le n, 1≤j≤m1\le j\le m.
  • Subtask 2 (30 points): 1≤n,m≤20001\le n,m\le 2000; 1≤ai,bj≤1091\le a_i,b_j\le 10^9 for all 1≤i≤n1\le i\le n, 1≤j≤m1\le j\le m.
  • Subtask 3 (50 points): 1≤n,m≤10000001\le n,m\le 1000000; 1≤ai,bj≤1091\le a_i,b_j\le 10^9 for all 1≤i≤n1\le i\le n, 1≤j≤m1\le j\le m.

Examples

Input

3 3
3 2 1
1 2 3

Output

4

Explanation

The original sequence a=[3,2,1]a=[3,2,1] already has three inversions: (3,2)(3,2), (3,1)(3,1) and (2,1)(2,1). They cannot be removed because the order of aa must remain intact.

One valid merged sequence is c=[1,2,3,2,1,3]c=[1,2,3,2,1,3], in which the original 3,2,13,2,1 remain in that order. Besides the three original inversions, exactly one additional inversion appears: the 22 from bb at position two lies before the 11 from aa at position five. The total is 3+1=43+1=4. The inserted value 22 must cause at least one inversion with either the original 33 or the original 11, so a result smaller than 44 is impossible.

No insertion order can achieve fewer than 44 inversions, so the answer is 4.