#FT0000136. Tòa nhà gặp nhau sớm nhất (Find Building Where Alice and Bob Can Meet)
Bài tập thuộc lộ trình
Mục lục đề ⌄
Tòa nhà gặp nhau sớm nhất (Find Building Where Alice and Bob Can Meet)
Find Building Where Alice and Bob Can Meet
Source: LeetCode
Version: Phuoc Hung OJ Extended
Problem Statement
There are buildings, indexed from to , arranged from left to right. Building has height .
A person standing at building may move to building if both and . The person may also remain at their starting building. Moving to a farther building does not require visiting the intervening buildings.
There are independent queries. In query , Alice starts at building and Bob at building . Find the smallest index of a building reachable by both people, possibly using several valid moves. Return if no such building exists.
They may meet at one person's starting building if the other can move there. If , they already meet there. All indices in the input and output are zero-based.
Input
The first line contains . The second line contains . Each of the next lines contains a query pair ; queries are independent.
Output
Print exactly lines. Line contains the smallest possible meeting building index for query , or if no meeting is possible.
Subtasks
- Subtask 1 (20 points): ; ; for every ; for each query.
- Subtask 2 (30 points): ; ; for every ; for each query.
- Subtask 3 (50 points): ; ; for every ; for each query.
Examples
Example 1
Input
6 5
6 4 8 5 2 7
0 1
0 3
2 4
3 4
2 2
Output
2
5
-1
5
2
Explanation
For , starting heights are and ; building has height and is reachable by both, and is the first such building. For , building (height ) is the first meeting point taller than both starting heights. For , Alice at height cannot move to a taller building to her right, so the result is . For , both reach building . For , they meet immediately at building .
Example 2
Input
8 5
5 3 8 2 6 1 4 6
0 7
3 5
5 2
3 0
1 6
Output
7
6
-1
4
6
Explanation
For , , so Alice can reach Bob directly at . For , the people start at heights and , and building (height ) is the first common destination. For , the person at index has height and cannot move farther right, so the answer is . For , index has height , exceeding both starting heights, so the answer is . For , Bob is already at index and Alice can move there, giving .