First, the number of odd number and even number in the $k$ large numbers before the interval is obtained.
If all are even, then the answer is the $k$ of the first large number.
Otherwise, either remove the smallest even number, add the largest odd number, or remove the smallest odd number, plus the largest even number.
Chairman Tree maintenance can be.
Time Complexity $o ((n+m) \log N) $.
#include <cstdio> #include <algorithm>using namespace Std;const int N=300010,m=6000000;int n,m,i,x,y,k,a[n ],b[n],tot,t[n],l[m],r[m],vc[m][2],c[2];long long v[m],sum,ans;inline Void Read (int&a) {char c;while (! ((C=getchar ()) >= ' 0 ') && (c<= ' 9 ')); a=c-' 0 '; while (((C=getchar ()) >= ' 0 ') && (c<= ' 9 ')) (a*= Ten) +=c-' 0 ';} inline int lower (int x) {int l=1,r=n,mid,t; while (l<=r) if (b[mid= (l+r) >>1]<=x) l= (t=mid) +1;else r=mid-1; return t;} int ins (int x,int a,int b,int c,int d) {int y=++tot; VC[Y][0]=VC[X][0],VC[Y][1]=VC[X][1]; vc[y][d&1]++,v[y]=v[x]+d; if (a==b) return y; int mid= (A+B) >>1; if (c<=mid) l[y]=ins (l[x],a,mid,c,d), R[y]=r[x];else l[y]=l[x],r[y]=ins (r[x],mid+1,b,c,d); return y;} inline void Ask (int x,int y,int k) {int a=1,b=n,mid,t; c[0]=c[1]=sum=0; while (a<b) {mid= (a+b) >>1,t=vc[r[x]][0]+vc[r[x]][1]-vc[r[y]][0]-vc[r[y]][1]; if (k<=t) a=mid+1,x=r[x],y=r[y]; else{k-=t; C[0]+=VC[R[X]][0]-VC[R[Y]][0]; C[1]+=VC[R[X]][1]-VC[R[Y]][1]; Sum+=v[r[x]]-v[r[y]]; B=mid,x=l[x],y=l[y]; }} c[::b[a]&1]+=k,sum+=1ll*::b[a]*k;} inline int kth (int x,int y,int k,int p) {int a=1,b=n,mid,t; while (a<b) {mid= (a+b) >>1,t=vc[r[x]][p]-vc[r[y]][p]; if (k<=t) A=mid+1,x=r[x],y=r[y];else k-=t,b=mid,x=l[x],y=l[y]; } return:: B[a];} int main () {for (read (n), i=1;i<=n;i++) read (A[i]), b[i]=a[i]; For (sort (b+1,b+n+1), i=1;i<=n;i++) T[i]=ins (T[i-1],1,n,lower (A[i]), a[i]); Read (m); while (m--) {read (x), read (y), read (k); if (k>y-x+1) {puts ("-1"); continue;} Ask (T[y],t[x-1],k); if (c[0]%2==0) {printf ("%lld\n", sum); continue;} for (ans=-1,i=0;i<2;i++) if (c[i]&&c[i^1]<vc[t[y]][i^1]-vc[t[x-1]][i^1]) Ans=max (ans,sum-kth (T[y), T[x-1],c[i],i) +kth (t[y],t[x-1],c[i^1]+1,i^1)); printf ("%lld\n", ans); } return 0;}
BZOJ4209: Watermelon King