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

#BS0000348. Thời điểm sớm nhất đánh dấu mọi chỉ số II (Earliest Second to Mark Indices II)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Thời điểm sớm nhất đánh dấu mọi chỉ số II (Earliest Second to Mark Indices II)

Earliest Second to Mark Indices II

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

Two integer arrays a1,a2,…,ana_1,a_2,\ldots,a_n and b1,b2,…,bmb_1,b_2,\ldots,b_m are given. No index of aa is marked initially. There are mm seconds, numbered from 11 through mm.

At second ss, choose exactly one of these actions:

  • Select an index ii (1≤i≤n1\le i\le n) and subtract 11 from aia_i.
  • Assign any nonnegative integer to absa_{b_s}.
  • Select an index ii (1≤i≤n1\le i\le n) satisfying ai=0a_i=0 and mark it.
  • Leave the state unchanged.

Find the earliest second by which every index is marked. If this cannot be achieved within mm seconds, the answer is -1.

Input

The first line contains two integers n,mn,m, the array lengths.

The second line contains nn integers a1,a2,…,ana_1,a_2,\ldots,a_n, the initial values.

The third line contains mm integers b1,b2,…,bmb_1,b_2,\ldots,b_m, where bsb_s is the index associated with second ss.

Output

Print one integer: the earliest second by which every index can be marked, or -1 if impossible.

Subtasks

  • Subtask 1 (20 points): 1≤n≤31\le n\le 3; 1≤m≤91\le m\le 9; 0≤ai≤40\le a_i\le 4 for all 1≤i≤n1\le i\le n; 1≤bs≤n1\le b_s\le n for all 1≤s≤m1\le s\le m.
  • Subtask 2 (30 points): 1≤n≤2001\le n\le 200; 1≤m≤2001\le m\le 200; 0≤ai≤1090\le a_i\le 10^9 for all 1≤i≤n1\le i\le n; 1≤bs≤n1\le b_s\le n for all 1≤s≤m1\le s\le m.
  • Subtask 3 (50 points): 1≤n≤50001\le n\le 5000; 1≤m≤50001\le m\le 5000; 0≤ai≤1090\le a_i\le 10^9 for all 1≤i≤n1\le i\le n; 1≤bs≤n1\le b_s\le n for all 1≤s≤m1\le s\le m.

Examples

Input 1

3 7
3 2 3
1 3 2 2 2 2 3

Output 1

6

Explanation

At seconds 1, 2 and 3, reset entries 1, 3 and 2, producing (0,2,3)(0,2,3), (0,2,0)(0,2,0) and (0,0,0)(0,0,0). Use the next three seconds to mark them. Each initially positive entry requires at least one change and one marking action, so six seconds are necessary.

Input 2

4 8
0 0 1 2
1 2 1 2 1 2 1 2

Output 2

7

Explanation

Mark the first two indices at seconds 1 and 2. Decrement entry 4 at seconds 3 and 4 and entry 3 at second 5, then mark the remaining indices at seconds 6 and 7. The last two entries never occur in bb, so three decrements and four markings are necessary.