Time Limit: 20000/15000 MS (Java/Others) Memory Limit: 524288/524288 K (Java/Others)
Total Submission(s): 3550 Accepted Submission(s): 1256
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
Source
2019 Multi-University Training Contest 4
Recommend
chendu
二分答案,判断p-mid,p+mid内的数的个数是否大于等于k
#include
#include
#include
#include
#define maxn 100005
#define N 1000005
using namespace std;
int lson[maxn*22];
int rson[maxn*22];
int root[maxn];
int sum[maxn*22];
int a[maxn];
int tot;
int t;
int n,m;
int build(int l, int r)
{
int rt = ++ tot;
int mid=(l+r)/2;
if (l < r)
{
lson[rt]=build(l,mid);
rson[rt]=build(mid+1,r);
}
return rt;
}
int update( int pre, int l, int r, int k) {
int now = ++tot;
sum[now] = sum[pre] + 1;
lson[now] = lson[pre];
rson[now] = rson[pre];
if(l=ql&&r<=qr)
return sum[now]-sum[pre];
int mid=(l+r)/2;
if(ql<=mid)
res+=query(lson[pre],lson[now],l,mid,ql,qr);
if(qr>mid)
res+=query(rson[pre],rson[now],mid+1,r,ql,qr);
return res;
}
int solve(int x, int len, int l, int r) {
int L = max(x - len, 1);
int R = min(x + len, N);
return query(root[l-1], root[r], 1, N, L, R);
}
int main()
{
scanf("%d", &t);
while (t--) {
int x,l, r, p, k, ans = 0;
tot = 0;
scanf("%d%d", &n, &m);
//root[0]=build(1,N);
for (int i = 1; i <= n; i++) {
scanf("%d", &x);
root[i]=update(root[i - 1], 1, N, x);
}
while (m--) {
scanf("%d%d%d%d", &l, &r, &p, &k);
l ^= ans, r ^= ans, p ^= ans, k ^= ans;
int L = 0, R = 1e6;
while (L < R) {
int mid = (L + R) / 2;
if (solve(p, mid, l, r) < k)
L = mid + 1;
else
R = mid;
}
printf("%d\n", ans = L);
}
}
return 0;
}