#FT0000080. Chèn tối ưu (Optimal Insertion)
Bài tập thuộc lộ trình
Mục lục đề ⌄
Chèn tối ưu (Optimal Insertion)
Optimal Insertion
Source: Codeforces
Version: Phuoc Hung OJ Extended
Problem Statement
You are given two integer sequences and . Insert all elements of at arbitrary positions in to form a sequence of length .
The relative order of the elements originally in must remain unchanged. The elements from , however, may appear in any order. You may insert them before the first element of , after its last element, or between consecutive elements; several elements may share an insertion gap.
An inversion is a pair of indices satisfying and . Equal elements never form an inversion. Determine the minimum possible number of inversions among all valid merged sequences.
Input
The first line contains integers , the lengths of the sequences.
The second line contains exactly integers in their original order.
The third line contains exactly integers . 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): ; for all , .
- Subtask 2 (30 points): ; for all , .
- Subtask 3 (50 points): ; for all , .
Examples
Input
3 3
3 2 1
1 2 3
Output
4
Explanation
The original sequence already has three inversions: , and . They cannot be removed because the order of must remain intact.
One valid merged sequence is , in which the original remain in that order. Besides the three original inversions, exactly one additional inversion appears: the from at position two lies before the from at position five. The total is . The inserted value must cause at least one inversion with either the original or the original , so a result smaller than is impossible.
No insertion order can achieve fewer than inversions, so the answer is 4.