1. 程式人生 > >bzoj3110: [Zjoi2013]K大數查詢(權值線段樹套區間線段樹)

bzoj3110: [Zjoi2013]K大數查詢(權值線段樹套區間線段樹)

題目
內層線段樹維護權值k在[l,r]內出現次數

#include<bits/stdc++.h>
using namespace std;
typedef unsigned int ll;
#define mid ((l+r)>>1)
const int N=200002,M=20000002;
int n,m,op,x,y,z,lz[M],L[M],R[M],cnt,rt[N];
ll sum[M];
inline char gc(){
    static char buf[100000],*p1=buf,*p2=buf;
    return p1==p2&&(p2=
(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++; } inline int rd(){ int x=0,fl=1;char ch=gc(); for (;ch<48||ch>57;ch=gc())if(ch=='-')fl=-1; for (;48<=ch&&ch<=57;ch=gc())x=(x<<3)+(x<<1)+(ch^48); return x*fl; } inline void wri(int a){if(a>=10)wri(a/10);putchar
(a%10|48);} inline void wln(int a){if(a<0)a=-a,putchar('-');wri(a),puts("");} void down(int t,int l,int r){ if (lz[t]){ if (!L[t]) L[t]=++cnt; if (!R[t]) R[t]=++cnt; sum[L[t]]+=(mid-l+1)*lz[t]; sum[R[t]]+=(r-mid)*lz[t]; lz[L[t]]+=lz[t]; lz[R[t]]+=
lz[t]; lz[t]=0; } } void update(int &t,int l,int r,int x,int y){ if (!t) t=++cnt; if (x<=l && r<=y){ sum[t]+=r-l+1; lz[t]++; return; } down(t,l,r); if (x<=mid) update(L[t],l,mid,x,y); if (mid<y) update(R[t],mid+1,r,x,y); sum[t]=sum[L[t]]+sum[R[t]]; } ll query(int t,int l,int r,int x,int y){ if (!t) return 0; if (x<=l && r<=y) return sum[t]; down(t,l,r); ll ans=0; if (x<=mid) ans+=query(L[t],l,mid,x,y); if (mid<y) ans+=query(R[t],mid+1,r,x,y); return ans; } void ins(){ int t=1,l=1,r=n; while (l<r){ update(rt[t],1,n,x,y); if (z<=mid) r=mid,t<<=1; else l=mid+1,t=t<<1|1; } update(rt[t],1,n,x,y); } int solve(){ int t=1,l=1,r=n; while (l<r){ ll p=query(rt[t<<1],1,n,x,y); if (z<=p) r=mid,t<<=1; else l=mid+1,t=t<<1|1,z-=p; } return l; } int main(){ n=rd(),m=rd(); for (;m--;){ op=rd(),x=rd(),y=rd(),z=rd(); if (op==1) z=n+1-z,ins(); else wln(n+1-solve()); } }