题解 P9809【[SHOI2006] 作业 Homework】

看到不好维护的取模相关信息,想到根号分治。设值域为 V,根号分治的阈值为 B

对于模数不超过 B 的情况,我们需要利用情况数为 O(B) 这一性质。在每次插入元素时动态维护所有情况的答案,查询时查表回答即可。

对于模数超过 B 的情况,我们需要利用商数个数为 O(VB) 这一性质。使用 set 维护集合中所有元素,每次查询时枚举所有可能的商数,二分查找这种情况下最小可能的余数。

B=O(V) 即可得到 O(NVlogN) 的并不优秀的复杂度。

事实上应该可以通过使用并查集代替 set 做到 O(NVα(N)),或者使用值域分块代替 set 做到 O(NV)。但反正能过,我懒得写了,如果有一天加强数据被卡常了那就不要参考下面的代码好了。

// Problem: P9809 [SHOI2006] 作业 Homework
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/P9809
// Memory Limit: 256 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

//By: OIer rui_er
#include <bits/stdc++.h>
#define rep(x, y, z) for(int x = (y); x <= (z); ++x)
#define per(x, y, z) for(int x = (y); x >= (z); --x)
#define debug(format...) fprintf(stderr, format)
#define fileIO(s) do {freopen(s".in", "r", stdin); freopen(s".out", "w", stdout);} while(false)
#define endl '\n'
using namespace std;
typedef long long ll;

mt19937 rnd(std::chrono::duration_cast<std::chrono::nanoseconds>(std::chrono::system_clock::now().time_since_epoch()).count());
int randint(int L, int R) {
    uniform_int_distribution<int> dist(L, R);
    return dist(rnd);
}

template<typename T> void chkmin(T& x, T y) {if(x > y) x = y;}
template<typename T> void chkmax(T& x, T y) {if(x < y) x = y;}

const int N = 3e5 + 5, B = 550;

int n, ans[B];
set<int> st;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    rep(i, 1, B - 1) ans[i] = i;
    for(cin >> n; n; --n) {
        string op; int x;
        cin >> op >> x;
        if(op == "A") {
            rep(i, 1, B - 1) chkmin(ans[i], x % i);
            st.insert(x);
        }
        else {
            if(x < B) cout << ans[x] << endl;
            else {
                int now = x;
                for(int i = 0; i < N; i += x) {
                    auto it = st.lower_bound(i);
                    if(it == st.end()) break;
                    chkmin(now, *it - i);
                }
                cout << now << endl;
            }
        }
    }
    return 0;
}
posted @   rui_er  阅读(42)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示