#BS0000348. Thời điểm sớm nhất đánh dấu mọi chỉ số II (Earliest Second to Mark Indices II)
Bài tập thuộc lộ trình
Mục lục đề ⌄
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 and are given. No index of is marked initially. There are seconds, numbered from through .
At second , choose exactly one of these actions:
- Select an index () and subtract from .
- Assign any nonnegative integer to .
- Select an index () satisfying and mark it.
- Leave the state unchanged.
Find the earliest second by which every index is marked. If this cannot be achieved within seconds, the answer is -1.
Input
The first line contains two integers , the array lengths.
The second line contains integers , the initial values.
The third line contains integers , where is the index associated with second .
Output
Print one integer: the earliest second by which every index can be marked, or -1 if impossible.
Subtasks
- Subtask 1 (20 points): ; ; for all ; for all .
- Subtask 2 (30 points): ; ; for all ; for all .
- Subtask 3 (50 points): ; ; for all ; for all .
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 , and . 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 , so three decrements and four markings are necessary.