[ 主席树 ] BZOJ4299

先考虑如何求出一个集合的答案。
将所有数从小到大加入。
假设当前已经可以构造出 [1,mx] 的所有数,然后加入一个数 x
x>mx+1 时, mx+1 就是答案。
xmx+1 时, mx 会加上 x
于是建一棵主席树,对于一个询问,每次求出 [1,mx+1] 的数的和更新 mx ,直到不满足条件。由于每次更新至少会加上 mx+1 ,即答案至少乘 2 ,更新次数是 O(logmax) 的。

#include<bits/stdc++.h>
using namespace std;
inline char nc(){
    static char buf[100000],*p1=buf,*p2=buf;
    return p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++;
}
inline void Read(int& x){
    char c=nc();
    for(;c<'0'||c>'9';c=nc());
    for(x=0;c>='0'&&c<='9';x=(x<<3)+(x<<1)+c-48,c=nc());
}
const int N=100010;
const int M=10000010;
const int INF=1e9;
int k,n,m,x,y;
int Rt[N],ls[M],rs[M],c[M],num;
void Update(int& x,int y,int l,int r,int z){
    x=++num;ls[x]=ls[y];rs[x]=rs[y];c[x]=c[y]+z;
    if(l==r)return;
    int Mid=l+r>>1;
    if(z<=Mid)Update(ls[x],ls[y],l,Mid,z);else Update(rs[x],rs[y],Mid+1,r,z);
}
int Query(int x,int y,int l,int r,int R){
    if(l>R)return 0;
    if(r<=R)return c[y]-c[x];
    int Mid=l+r>>1;
    return Query(ls[x],ls[y],l,Mid,R)+Query(rs[x],rs[y],Mid+1,r,R);
}
int main(){
    Read(n);
    for(int i=1;i<=n;i++)Read(x),Update(Rt[i],Rt[i-1],1,INF,x);
    Read(m);
    while(m--){
        Read(x);Read(y);
        k=1;
        while(1){
            int t=Query(Rt[x-1],Rt[y],1,INF,k);
            if(t<k)break;
            k=t+1;
        }
        printf("%d\n",k);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值