P9809题解

· · 题解

题意:你需要支持加入一个数,查找区间模当前数的最小值。

很明显的根号分治。

我们设对于 B 根号分治。

对于小于等于 B 的询问,我们直接预处理出每个数的值,用数组存起来,时间复杂度 O(nB)。

对于大于B的询问,我们用 set 维护序列里的数,枚举当前数的所有倍数,二分找第一个大于等于它的,时间复杂度 O(n\frac V B \log n)。

此时插入的复杂度 O(nB\log n),查询的复杂度 O(n\frac V B\log n) 或者 O(1)。

我们取 B=O(\sqrt V),可得时间复杂度为 O(n\sqrt V\log n)。

#include<bits/stdc++.h>
using namespace std;
#define int long long
#define y1 Y1
#define debug(...) fprintf(stderr,__VA_ARGS__)
#define min(a,b) (a<b?a:b) 
#define max(a,b) (a>b?a:b)
#define P pair<int,int>
#define x first
#define y second
#define modd(x) (((x)%mod+mod)%mod) 
#define rd read()
#define lowbit(x) ((x)&(-x))
#define abs(x) ((x)<0?-(x):(x))
mt19937 rnd(time(0));
inline int read(int u=0, char c=getchar(), bool f=false){
    for (;!isdigit(c);c=getchar()) f|=c=='-';
    for (;isdigit(c);c=getchar()) u=(u<<1)+(u<<3)+c-'0';
    return f?-u:u;
}
inline void wt(int x){
    if(x<0) x=-x,putchar('-');
    if(x>9) wt(x/10);
    putchar(x%10+48);
}
inline void wt(int x,char k){wt(x),putchar(k);}
const int inf=~0U>>1,linf=~0ULL>>1; 
const int mod=998244353,g=3,gi=332748118;
const int N=3e5+10,B=600;
int n,ans[B+10];
set<int>s;
main(){
    n=rd;
    memset(ans,0x3f,sizeof ans);
    while(n--){
        char c;
        int x;
        cin>>c>>x;
        if(c=='A'){
            s.insert(x);
            for(int i=1;i<=B;i++) ans[i]=min(ans[i],x%i);
        }
        else{
            if(x<=B){
                wt(ans[x],'\n');
                continue;
            }
            int sum=inf;
            for(int i=0;;i+=x){
                auto it=s.lower_bound(i);
                if(it==s.end()) break;
                sum=min(sum,(*it)-i);
            }
            wt(sum,'\n');
        }
    }
    return 0;
}