Time Limit: 20000/15000 MS (Java/Others) Memory Limit: 524288/524288 K (Java/Others)
Problem Description
You have an array: a1, a2, …, an and you must answer for some queries.
For each query, you are given an interval [L, R] and two numbers p and K. Your goal is to find the Kth closest distance between p and aL, aL+1, …, aR.
The distance between p and ai is equal to |p - ai|.
For example:
A = {31, 2, 5, 45, 4 } and L = 2, R = 5, p = 3, K = 2.
|p - a2| = 1, |p - a3| = 2, |p - a4| = 42, |p - a5| = 1.
Sorted distance is {1, 1, 2, 42}. Thus, the 2nd closest distance is 1.
Input
The first line of the input contains an integer T (1 <= T <= 3) denoting the number of test cases.
For each test case:
The first line contains two integers n and m (1 <= n, m <= 10^5) denoting the size of array and number of queries.
The second line contains n space-separated integers a1, a2, …, an (1 <= ai <= 10^6). Each value of array is unique.
Each of the next m lines contains four integers L’, R’, p’ and K’.
From these 4 numbers, you must get a real query L, R, p, K like this:
L = L’ xor X, R = R’ xor X, p = p’ xor X, K = K’ xor X, where X is just previous answer and at the beginning, X = 0.
(1 <= L < R <= n, 1 <= p <= 10^6, 1 <= K <= 169, R - L + 1 >= K).
Output
For each query print a single line containing the Kth closest distance between p and aL, aL+1, …, aR.
Sample Input
1 | 1 |
Sample Output
1 | 0 |
思路分析
题目意思是说,给定一段序列,每次求区间[L,R]的数与P的差的绝对值,对其排序后的第K个差值是多少。(后面的L,R,P,K要用之前的答案异或得到,所以一旦前面错了,后面就Game Over了,甚至会RE【别问我为什么quq】)
首先考虑到时间限制,虽然给了15s看上去绰绰有余,实际上偌大的数据量还是不能暴力去算,所以就想到了线段树这个万能的东西!它可以把查询压缩到O(logn),但这样复杂度还是有点高,所以再考虑二分一下以p为中心的半径,即每次验证[p-mid,p+mid]区间内的数的个数是不是符合要求,这样总体的复杂度就是O(mloglogn),是不是感觉很赞呢~
用主席树(一说叫权值线段树)查询十分方便,我们只需要以数据初始的id为基建树,然后再一阵基本操作就行!
反正具体的看代码就行!
Code
1 |
|