题解:AT_abc449_e [ABC449E] A += v

· · 题解

思路

我们换句话描述一下它的放数方式:

我们发现对于一个数来说,在最开始只能最多放入 n 次,我们再次转化:

看到这里,我们就应该想到这道题需要离线处理,因为后面的操作对之前的操作有继承性,设 i 出现了 cnt_i 次, 对于数 i,从第 cnt_i+1 次插入开始就会一直留在刚刚插入的数的序列中,显然根据题意,我们要求刚刚插入的数的序列升序。

我们维护一个当前序列的长度 p,判断对于一个数而言是否在我们需要特殊处理的区间中,对于具体找出这个位置的数,我们维护一个长度为 m 树状数组,对于第 i 个位置的前缀和为截止到第 i 个位置时在刚刚插入的数的序列中的位置,序列从 1 开始编号,如果 i 不在序列,前缀和要求与 i-1 相等,这样我们就可以通过树状数组上二分得出当前位置确切的数值。

Code

#include <cstdio>
#include <algorithm>
#include <vector>
#define ll unsigned long long
#define ui unsigned int
#define N 500005
using namespace std;
const ui _2[19]= { 1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192, 16384, 32768, 65536, 131072, 262144 } ;
template<typename T> void read(T& x) {
    x=0;
    char ch=getchar();
    while(ch<'0'||ch>'9')
        ch=getchar();
    while(ch>='0'&&ch<='9')
        x=(x<<3)+(x<<1)+(ch&15), ch=getchar();
}
template<typename T, typename... Args> void read(T& x, Args&... args) {
    read(x);
    read(args...);
}
template<typename T> void write(T x) {
    if(x==0) {
        putchar('0');
        return ;
    }
    ui a[25], t=0;
    while(x)
        a[++t]=x%10, x/=10;
    while(t)
        putchar(a[t--]|48);
}
ui n, m, a[N], q, j, cnt[N], f[N], ans[N], g[N], lgm;
ll x[N], p;
vector<ui> G[N];
void update(ui i) {
    for(; i<=m; i+=(i&-i))
        ++f[i];
}
ui getsum(ui i) {
    ui res=0;
    while(i)
        res+=f[i], i-=(i&-i);
    return res;
}
bool cmp(ui a, ui b) {
    return x[a]<x[b];
}
int main() {
    read(n, m);
    p=n, q=m;
    while((q>>=1))
        ++lgm;
    for(ui i=1; i<=n; ++cnt[a[i++]])
        read(a[i]);
    for(ui i=1; i<=m; ++i)
        G[cnt[i]].push_back(i);
    read(q);
    for(ui i=1; i<=q; g[i]=i, ++i)
        read(x[i]);
    sort(g+1, g+1+q, cmp);
    for(ui k=1; k<=q; ++k) {
        ui i=g[k];
        if(x[i]<=n)
            ans[i]=a[x[i]];
        else {
            while(true) {
                if(p>=x[i]) {
                    ui M=getsum(m);
                    ui w=M+x[i]-p;
                    ui k=_2[lgm], s=0, t=lgm, l;
                    while(t--) {
                        if(k>m || f[k]+s>w)
                            k-=_2[t];
                        else if(f[k]+s<w)
                            s+=f[k], k+=_2[t];
                        else
                            l=k, k-=_2[t];
                    }
                    if(f[k]+s==w)
                        l=k;
                    ans[i]=l;
                    break;
                }
                if(j<=n) {
                    for(ui t : G[j])
                        update(t);
                    ++j;
                    p+=getsum(m);
                }
                else {
                    ans[i]=(x[i]-p-1)%m+1;
                    break;
                }
            }
        }
    }
    for(ui i=1; i<=q; ++i)
        write(ans[i]), putchar('\n');
    return 0;
}