/*
划分树:解题类型单一,给出10^5个点,给你 q 个查询,每次查询出[l,r] 中第 k 大的值。
划分树:
主系列 4 3 2 5 8 7 6 1 9
排序后 1 2 3 4 5 6 7 8 9 中位数是 5
划左边 4 3 2 5 1 划右边 8 7 6 9
划左边 3 2 1 划右边 4 5 划左边 6 7 划右边 8 9
。。。。。。。 。。。。。。
参考博客:http://www.2cto.com/kf/201210/160552.html
*/
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstdio>
using namespace std;
#define manx 100009
int x[manx],tree[20][manx];
int sum_left[20][manx];
__int64 lsum[20][manx];
__int64 dp[manx];
void make(int level,int left,int right){
if(left==right) return ;
int mid = (left+right)>>1;
int num = mid - left + 1;
for(int i=left;i<=right;i++){
if(tree[level][i]<x[mid])
num--;
}
int lpos = left, rpos = mid+1;
for(int i=left; i<=right; i++){
if(i==left){
lsum[level][i]=0; 初始化
sum_left[level][i]=0;
}
else {
lsum[level][i]=lsum[level][i-1];初始化
sum_left[level][i]=sum_left[level][i-1];
}
if(tree[level][i]<x[mid]){
sum_left[level][i]++;
lsum[level][i] += tree[level][i];///放在左边的全部加上
tree[level+1][lpos++] = tree[level][i];
}
else if(tree[level][i]>x[mid])
tree[level+1][rpos++] = tree[level][i];
else {
if(num > 0){
num--;
sum_left[level][i]++;
lsum[level][i] += tree[level][i];///出现与中位数相等的放在左边的也要加上
tree[level+1][lpos++]=tree[level][i];
}
else tree[level+1][rpos++]=tree[level][i];
}
}
make(level+1,left,mid);
make(level+1,mid+1,right);
}
__int64 numl,suml; // 比中位数小的个数 和 总和
__int64 query(int level,int left,int right,int l,int r,int k){
if(l==r) return tree[level][l];
int s, ss, mid = (left+right)>>1;
__int64 temp=0;
if(left==l){
s = 0;
ss = sum_left[level][r];
temp = lsum[level][r]; ///
}
else {
temp = lsum[level][r]-lsum[level][l-1]; /// 求一小段的值
s = sum_left[level][l-1];
ss = sum_left[level][r]-s;
}
int newl,newr;
if(k<=ss){
newl = left + s;
newr = left + s + ss - 1;
return query(level+1,left,mid,newl,newr,k);
}
else {
numl += ss;
suml += temp; ///加上某段求得和
newl = mid + (l-left-s+1);
newr = mid + (r-left-s-ss+1);
return query(level+1,mid+1,right,newl,newr,k-ss);
}
}
int main(){
int n,q,ca=0,t;
scanf("%d",&t);
while(t--){
scanf("%d",&n);
dp[0]=0;
for(int i=1;i<=n;i++){
scanf("%d",&tree[0][i]);
x[i] = tree[0][i];
dp[i] = x[i] + dp[i-1];
}
sort(x+1,x+n+1);
make(0,1,n);
scanf("%d",&q);
printf("Case #%d:\n",++ca);
while(q--){
int l,r,k;
scanf("%d%d",&l,&r);
l++, r++;
k = (r-l)/2 + 1;
numl = suml = 0;
__int64 val = query(0,1,n,l,r,k);
__int64 sum = val*numl - suml;
numl = r-l+1-numl;
suml = dp[r]-dp[l-1]-suml;
sum += suml - numl*val;
printf("%I64d\n",sum);
}
printf("\n");
}
}
HDU 3473 划分树求某段区间的和
最新推荐文章于 2020-08-30 12:56:40 发布