题解 P4587 【[FJOI2016]神秘数】

· · 题解

讲一个好理解的方法。

约定变量:

我们来挖掘这题的性质。 ## $1:\ $对于一个新加入的数$x

若x\leq \text{pos}+1,那么\text{pos}可以扩大成\text{pos}+x

证明:非常简单,对于每一个y\in[1,\text{pos}],有两个选择:

y+=x:\ $值域变为$[1+x,\text{pos}+x]

不变\ :\ 值域依然为[1,\text{pos}]

x$单独为一个数$\ :\ $值域为$[x,x]

三者的并集为[1,\text{pos}+x]。

若x>\text{pos}+1,那么无法扩大

比较显然,因为多了一个x依旧拼不出\text{pos}+1(x>\text{pos}+1)

这个性质有什么用呢?

2:\ 对于区间[l,r]

我们把区间里的数从小到大拿出来。排序,设为a_1,a_2,...

必有a_1=1

显然。。。

我们一个一个数从小到大加入(先加入所有的1,随后是2...)。

我们设\text{mx}为已经在这个集合内数的上界。

我们要新加入的数一定\in [\text{mx}+1,\text{pos}+1]

因为之前[1,\text{mx}]里的所有数都加入过了,继续加入就重复了!

而且根据刚才讲的,加入[\text{pos}+2,+\infty]对答案无贡献。

我们可以把这个值域内所有的数全部加入,设这个值域[\text{mx}+1,\text{pos}+1]的所有数和为\text{Sum},整个区间就可以扩大。

此时\text{mx}变为\text{pos}+1,而原来的\text{pos}则要加上\text{Sum}(就是刚才讲的性质)

如果\text{Sum}=0答案就是\text{pos}+1

求值域和可以用权值线段树。然而这个是区间查询,所以我们使用主席树。

时间复杂度分析

发现\text{pos}的变换幅度很大,每一次加上\text{pos}'+1(上一次的\text{pos})

这是一个倍增的复杂度。所以复杂度为O(mlog_{2}^2A)

其中A是a数组的最大值。

#include<bits/stdc++.h>
#define ll long long
using namespace std;
inline char gc(){
    static char now[1<<16],*S,*T;
    if (T==S){T=(S=now)+fread(now,1,1<<16,stdin);if (T==S) return EOF;}
    return *S++;
}
inline ll read(){
    register ll x=0,f=1;char ch=gc();
    while (!isdigit(ch)){if(ch=='-')f=-1;ch=gc();}
    while (isdigit(ch)){x=(x<<3)+(x<<1)+ch-'0';ch=gc();}
    return (f==1)?x:-x;
}
int cnt,root[1000001],n,m;
const int inf=1e9;
struct node{
    int l,r,sum;
}seg[5000001];
#define mid ((lb+rb)>>1)
void update(int &rt,int lb,int rb,int x){
    seg[++cnt]=seg[rt];rt=cnt;seg[rt].sum+=x;
    if (lb==rb) return;
    (mid>=x?update(seg[rt].l,lb,mid,x):update(seg[rt].r,mid+1,rb,x));
}
int query(int i,int j,int lb,int rb,int l,int r){
    if (!(seg[j].sum-seg[i].sum)||r<lb|rb<l) return 0;
    if (lb>=l&&rb<=r) return (seg[j].sum-seg[i].sum);
    return query(seg[i].l,seg[j].l,lb,mid,l,r)+query(seg[i].r,seg[j].r,mid+1,rb,l,r);
}
int main(){
    n=read();
    for (int i=1;i<=n;i++){
        root[i]=root[i-1];
        update(root[i],1,inf,read());
    }
    m=read();
    while (m--){
        int l=read(),r=read();
        int mx=0,pos=0;
        for (int Sum;;){
            Sum=query(root[l-1],root[r],1,inf,mx+1,pos+1);
            if (!Sum) break;
            mx=pos+1;pos+=Sum;
        }
        printf("%d\n",pos+1);
    }
    return 0;
}