K-th Closest Distance
Time Limit: 20000/15000 MS (Java/Others) Memory Limit: 524288/524288 K (Java/Others)
Total Submission(s): 2669 Accepted Submission(s): 950
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
5 2
31 2 5 45 4
1 5 5 1
2 5 3 2
Sample Output
0
1
题意:给定一个序列,每次询问给出区间L,R和p,k求p减去区间内的数的绝对值的第K小是多少。
解法之一:建立主席树或者线段树,对于给定的区间,二分答案mid, 查找区间内p-mid~p+mid这个值域内的数是否大于K。
#include <iostream>
#include <bits/stdc++.h>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
#define maxn 1000010
int tot;
struct node
{
int l,r,v;
}tree[maxn*25];
int root[maxn];
int a[100010];
int update(int rt,int l,int r,int v,int ro)
{
int now=++tot;
tree[now]=tree[ro];
tree[now].v=tree[ro].v+1;
if(l==r) return now;
int mid=(l+r)>>1;
if(mid>=v){
tree[now].l=update(rt<<1,l,mid,v,tree[now].l);
}
else tree[now].r=update(rt<<1|1,mid+1,r,v,tree[now].r);
return now;
}
int query(int rt,int l,int r,int L,int R,int x,int y)
{
if(l>=L&&r<=R){
return tree[y].v-tree[x].v;
}
int mid=(l+r)>>1;
int ans=0;
if(mid>=L){
ans+=query(rt<<1,l,mid,L,R,tree[x].l,tree[y].l);
}
if(mid<R) ans+=query(rt<<1|1,mid+1,r,L,R,tree[x].r,tree[y].r);
return ans;
}
int main()
{
int T;
scanf("%d",&T);
while(T--){
int n,m;
scanf("%d %d",&n,&m);
for(int i=1;i<=n;i++){
scanf("%d",&a[i]);
}
tot=0;
for(int i=1;i<=n;i++) {
root[i]=update(1,1,1000000,a[i],root[i-1]);
}
int pre=0;
int L,R,p,k,l,r;
for(int i=1;i<=m;i++){
scanf("%d %d %d %d",&L,&R,&p,&k);
L=L^pre,R=R^pre,p=p^pre,k=k^pre;
int st=0,en=1e7;
while(en>st){
int mid=(st+en)>>1;
int t=query(1,1,1000000,p-mid,p+mid,root[L-1],root[R]);
if(t>=k){
en=mid;
}
else st=mid+1;
}
printf("%d\n",st);
pre=st;
}
}
return 0;
}