Day 2 The Prisoner of Azkaban

3

3 votes
Binary indexed tree, Merge sort
Problem

Sirius Black, the prisoner of Azkaban wants to find Harry Potter so he tries to escape from the prison cell. The prison cells are arranged in the following manner:
There are two rows of prison cells facing each other, each having N numbers of cells.

Each prison cell has some escape value. Let E be the escape value and K be the index of the prison cell in which Sirius Black is. Sirius Black can escape from a prison cell only if that prison cell is in the opposite row and its escape value is less than or equal to E. Further, he can escape from the prison if its index is less than or equal to K.
You have to answer Q queries.

Input
First-line contains two space-separated integers N and Q.
Second-line contains N space-separated integers A11,A12,A13,........A1N , escape values of 1st-row's prison cells.
Third-line contains N space-separated integers A21,A22,A23,........A2N, escape values of 2nd-row's prison cells.
Next, Q Line Contain two space-separated integer T and K, Where T defines the row number of the prison (can be either 1 or 2) and K defines the index of the prison cell where Sirius Black is.

Output

For each query containing row number 1, print the number of prison cell such that it is less than or equal to A1[K] in the range A2[1]..A2[K].
For each query containing row number 2, print the number of prison cell such that it is less than or equal to A2[K] in the range A1[1]..A1[K].

Constraints
1N,Q1061A1[i],A2[i]1061KN

Sample Input
10 10
8 4 1 2 4 1 9 4 1 2
8 5 2 9 3 8 1 3 1 6
2 1
1 1
1 2
2 3
1 4
2 5
2 6
1 7
1 8
1 9
Sample Output
1
1
0
1
1
2
6
7
4
2
Time Limit: 3
Memory Limit: 256
Source Limit:
Explanation

For Third query = 1 2 
Count of prison cells having escape values less than or equal to A1[2] =4 in range A2[1] =8, A2[2] =5 is 0
OR
NOTHING  A1[2]

 
For Seventh query = 2 6
Count of prison cells having escape values less than or equal to A2[6] =8 in range A1[1], A1[2], A1[3], A1[4], A1[5], A1[6] is 6
OR

A1[1], A1[2], A1[3], A1[4], A1[5], A1[6]  A2[6]

For Ninth query = 1 8
Count of prison cells having escape values less than or equal to A1[8] =4 in range A2[1], A2[2], A2[3], A2[4], A2[5], A2[6], A2[7], A2[8] is 4
OR
A2[3], A2[5], A2[7], A2[8]   A1[8]

Editor Image

?