http://acm.hdu.edu.cn/showproblem.php?pid=6621
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
5 2
31 2 5 45 4
1 5 5 1
2 5 3 2
Sample Output
0
1
一开始看169数字很小就写的主席树从中间开始单点询问,但是T了,应该是主席树加区间求和
每次得到p-mid到p+mid的和,二分得出答案
#include <bits/stdc++.h>
using namespace std;
const int N=1e5+5;
const int M=1e6;
struct node
{
int l,r;
int sum;
}tree[N*55];
int rt[N],tot;
int n,m,a[N];
int update(int pre,int pl,int pr,int pos)
{
int cur=++tot;
tree[cur]=tree[pre];
tree[cur].sum++;
if(pl==pr)
return cur;
int mid=(pl+pr)>>1;
if(pos<=mid)
tree[cur].l=update(tree[pre].l,pl,mid,pos);
else
tree[cur].r=update(tree[pre].r,mid+1,pr,pos);
return cur;
}
int k,cnt;
int query(int pl,int pr,int l,int r,int rt,int lt)
{
if(pl<=l&&r<=pr)
return tree[rt].sum-tree[lt].sum;
int mid=(l+r)>>1;
int res=0;
if(pl<=mid)
res+=query(pl,pr,l,mid,tree[rt].l,tree[lt].l);
if(pr>mid)
res+=query(pl,pr,mid+1,r,tree[rt].r,tree[lt].r);
return res;
}
int main( )
{
int T,prex;
int l,r,p;
int pl,pr,mid;
scanf("%d",&T);
while(T--)
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i]);
rt[i]=update(rt[i-1],1,M,a[i]);
}
prex=0;
while(m--)
{
scanf("%d%d%d%d",&l,&r,&p,&k);
l=l^prex;r=r^prex;p=p^prex;k=k^prex;
pl=0,pr=M;
while(pl<=pr)
{
mid=(pl+pr)>>1;
if(query(max(1,p-mid),min(M,p+mid),1,M,rt[r],rt[l-1])>=k)
{
prex=mid;
pr=mid-1;
}
else pl=mid+1;
}
printf("%d\n", prex);
}
}
}