[RCOI] 集合的数 #1 题解

· · 个人记录

[RCOI] 集合的数 #1

题目描述

维护一个可重集合,初始有 n 个元素,所有元素 \le k。支持 m 次操作:

对每个 max 操作输出答案。

核心思想

直接暴力处理 Change 操作会超时(最坏 O(mk))。我们采用根号分治的方法:

所以,当前任何一个数 y 的出现次数都可以用:

\text{cnt}[y] = \text{t}[y] + \sum_{\substack{d \le p \\ d \mid v}} \text{tag}[y]

其中 t[y] 由 Push 和 Change 贡献的次数,用树状数组维护。

操作实现

1. Push x

直接 T.add(x, 1),无需动脑。

2. Change x

3. Delete x

先计算当前总数:

int s=T.query_one(x);//单点查询
for(int d=1;d<=p;d++)if(x%d==0)s+=tag[d];

最后,执行 T.add(x,-s) 。

4. Max x

答案有两部分组成:

  1. t:直接用树状数组查询 x \sim k 的区间和。

  2. tag:对每个 d \le B,答案很显然为为 \text{tag}[d] \times \left( \left\lfloor \frac{k}{d} \right\rfloor - \left\lfloor \frac{x}{d} \right\rfloor \right)

代码

#include<bits/stdc++.h>

#define int long long

using namespace std;

const int N=2e5+5; 

int n,m,a,s[N],tag[N],MaxN,Sq;

struct Tree{
    int t[N],a[N];
    int lb(int x){return x&(-x);}
    void init(){memset(t,0,sizeof(t)),memset(a,0,sizeof(a));}
    void add(int x,int y){a[x]+=y;while(x<=MaxN)t[x]+=y,x+=lb(x);} 
    int query(int x){int s=0;while(x)s+=t[x],x-=lb(x);return s;}
    int query_one(int x){return a[x];} 
}T;

int get_sum(int x){
    int res=T.query_one(x);
    for(int i=1;i<=Sq;i++)
        if(x%i==0)res+=tag[i];
    return res; 
}

void add(int x){
    if(x<=Sq)tag[x]++;
    else{
        for(int i=x;i<=MaxN;i+=x)
            T.add(i,1);
    } 
    return;
}

int query(int x){
    int res=T.query(MaxN)-T.query(x);
    for(int i=1;i<=Sq;i++)
        res+=tag[i]*((MaxN)/i-x/i);
    return res;
}

void del(int x){
    int s=get_sum(x);
    T.add(x,-s);
    return;
}

signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0);cout.tie(0);
    cin>>n>>m>>MaxN;Sq=sqrt(MaxN);
    T.init();
    for(int i=1;i<=n;i++){
        cin>>a;
        T.add(a,1); 
    }
    while(m--){
        string op;
        cin>>op;
        if(op=="Push"){
            int x;cin>>x;
            T.add(x,1);
        }else if(op=="Delete"){
            int x;cin>>x;
            del(x);
        }else if(op=="Change"){
            int x;cin>>x;
            add(x);
        }else{
            int x;cin>>x;
            cout<<query(x)<<"\n";
        }
    }
    return 0;

做个总结: 出题人真是个大菜鸡,出的题目太简单了,但我就是出题人。