Replace Sort

시간 제한3초메모리 제한1024 MB

요약
B의 서로 다른 값을 각각 최대 한 번 사용해 A의 원소를 교체하여 A를 오름차순으로 정렬할 때, 필요한 최소 교체 횟수를 구한다.
난이도

어려움10점 중 8점

유형
동적 계획법, 이분 탐색, 정렬, 그리디
정답자
아직 제출이 없습니다

문제

Consider an array AA and a set BB of integers such that all numbers in AA and BB are distinct. Your task is to turn AA into a sorted array. To do this you can take any number from BB and replace any element of AA with it. You can perform this operation any number of times, but each element of BB can be used at most once.

Determine the minimum number of operations needed to turn AA into a sorted array, or determine that it is impossible.

입력

The first line of input contains two integers NN and MM (1≤N,M≤5⋅1051 \le N, M \le 5 \cdot 10^5) --- the sizes of AA and BB respectively.

The second line contains NN integers A_1,A_2,…,A_NA\_1, A\_2, \ldots, A\_N.

The third line contains MM integers B_1,B_2,…,B_MB\_1, B\_2, \ldots, B\_M.

All the (N+M)(N + M) elements are distinct, positive and do not exceed 10910^9.

출력

If it is impossible to turn AA into a sorted array, print −1-1. Otherwise, print the minimum number of operations needed.

힌트

In all three examples, the issue is that 13>1013 > 10, so we have to change at least one of them.

In the first one, we can decrease 1313 by replacing it with 55, but it breaks the other side, so there is no solution.

In the second one, we also have 44, which we can use to fix the broken side. It is impossible to do with less than 22 operations.

In the third example we can finally increase the last element, thus fixing AA in 1 operation.

예제3

  1. 예제 1

    입력
    4 1
    2 6 13 10
    5
    
    예상 출력
    -1
    
  2. 예제 2

    입력
    4 2
    2 6 13 10
    5 4
    
    예상 출력
    2
    
  3. 예제 3

    입력
    4 3
    2 6 13 10
    5 4 19
    
    예상 출력
    1