#d1602. 丹钓战
丹钓战
Dandiao Stack Game
Problem Description
There are pairs , numbered from to .
There is an initially empty stack . When inserting a pair , first keep popping the top element until the stack is empty or the top element satisfies and , then push onto the stack.
A pair is called "successful" if, after being pushed, it is the only element in the stack.
There are queries . If the pairs with indices in are pushed onto the stack in increasing index order, how many of them are "successful"? The queries are independent of each other.
Input Format
The first line contains two positive integers .
The second line contains positive integers, the values .
The third line contains positive integers, the values .
The following lines each contain two positive integers , describing one query.
Output Format
lines, each containing a non-negative integer: the answer to the corresponding query.
Sample Input
10 4
3 1 3 1 2 3 3 2 1 1
10 10 2 9 7 5 4 7 6 1
1 4
7 8
7 10
1 8
Sample Output
3
2
2
3
Sample Explanation
Take the first query as an example.
Initially the stack is .
After pushing pair , the stack is ; it has only one element, so this pair is "successful".
When pushing pair , the value of the top element is not greater than that of pair , so we pop. Now the stack is empty; pair is pushed, the stack becomes , so this pair is "successful".
When pushing pair , the top element has a different value and a larger value, so no popping is needed; pair is pushed directly, the stack becomes , which has multiple elements, so this pair is not "successful".
When pushing pair , the value of the top element is smaller, so we pop. After popping, the top element has the same value as , so we continue popping. Now the stack is empty; pair is pushed, the stack becomes , so this pair is "successful". In total pairs are "successful", hence the answer is .
Constraints
$1 \leq n, q \leq 5 \times 10^5, 1 \leq a_i, b_i \leq n, 1 \leq l_i \leq r_i \leq n$.