Question:
A fixed number M queries each time an X value is selected to make the absolute value and minimum of the difference between each element and X in the range [L, R]
Ideas:
If the value of X is the median of numbers in [L, R], the question becomes the number (R-l + 1 + 1) in [L, R) /2 A small number is a few. Because the numbers are static, the tree can be divided.
Then ans = num (<= x) * X-sum (<= x) + sum (> X)-num (> X) * x
Since sum can be obtained by prefix and mutual num, and the interval size can be used to calculate each other, we only need to require X, sum (<= x), num (<= X)
The basic tree can solve the problem of x and num.
If sum is to be calculated, a sum [I] [J] array is maintained to indicate the sum of the numbers from layer I to position J to the left subtree.
Code:
#include<cstdio>#include<cstring>#include<algorithm>using namespace std;#define N 101000#define M 30typedef __int64 LL;int tree[M][N],toleft[M][N],sorted[N];LL sum[M][N],before[N];int t,T,n,m;void build(int l,int r,int dep){if(l==r) return ;int i,mid=(l+r)>>1;int y=sorted[mid],same=mid-l+1,lpos=l,rpos=mid+1;for(i=l;i<=r;i++){if(tree[dep][i]<y) same--;}for(i=l;i<=r;i++){ sum[dep][i]=sum[dep][i-1];if(tree[dep][i]<y) { tree[dep+1][lpos++]=tree[dep][i]; sum[dep][i]+=tree[dep][i]; }else if(tree[dep][i]==y&&same>0){tree[dep+1][lpos++]=tree[dep][i];same--;sum[dep][i]+=tree[dep][i];}else tree[dep+1][rpos++]=tree[dep][i];toleft[dep][i]=toleft[dep][l-1]+lpos-l;}build(l,mid,dep+1);build(mid+1,r,dep+1);}int ansnum;LL anssum;int query(int L,int R,int l,int r,int dep,int k){if(l==r) return tree[dep][l];int mid=(L+R)>>1,amt=toleft[dep][r]-toleft[dep][l-1];if(amt>=k){int fl=L+toleft[dep][l-1]-toleft[dep][L-1];int fr=fl+amt-1;return query(L,mid,fl,fr,dep+1,k);}else{ ansnum+=amt; anssum+=sum[dep][r]-sum[dep][l-1];int fr=r+toleft[dep][R]-toleft[dep][r];int fl=fr-(r-l-amt);return query(mid+1,R,fl,fr,dep+1,k-amt);}}int main(){ int i,l,r; LL middle; scanf("%d",&T); for(t=1;t<=T;t++) { printf("Case #%d:\n",t); scanf("%d",&n); for(i=1;i<=n;i++) { scanf("%d",&sorted[i]); before[i]=before[i-1]+sorted[i]; tree[0][i]=sorted[i]; } sort(sorted+1,sorted+1+n); build(1,n,0); scanf("%d",&m); while(m--) { scanf("%d%d",&l,&r); l++; r++; ansnum=0; anssum=0; middle=(LL)(query(1,n,l,r,0,(r-l+2)/2)); printf("%I64d\n",(before[r]-before[l-1]-anssum)-anssum-middle*(r-l+1-ansnum-ansnum)); } puts(""); }return 0;}
HDU 3473 Minimum Sum