题解:P9809 [SHOI2006] 作业 Homework
本篇题解同时也是我的笔记。
下称
首先要做
如果答案比较小,设一个阈值为
既然这个余数
我们不妨枚举
所以我们的算法复杂度是
实现集合查找可以用现成的 STL 模版 set<int>,s.insert() 插入,s.lower_bound() 查找。查找的时候记得判是否出界。写起来十分方便且跑得很快(最慢的点不到 200ms)。
好像可以去掉
#include<bits/stdc++.h>
using namespace std;
const int K = 548; // ≈ sqrt(300000)
int T, a[550];
set<int> s;
signed main() {
for (int i = 1; i <= K; i++) a[i] = i - 1;
scanf("%d", &T);
while (T--) {
char op; while (!isupper(op = getchar()));
int x; scanf("%d", &x);
if (op == 'A') {
for (int i = 1; i <= K; i++)
a[i] = min(a[i], x % i);
s.insert(x);
} else {
if (x <= K) {
printf("%d\n", a[x]);
} else {
int ans = x - 1;
for (int t = 0; t <= 300000 / x; t++) {
auto it = s.lower_bound(t * x);
if (it != s.end()) ans = min(ans, *it - t * x);
}
printf("%d\n", ans);
}
}
}
return 0;
}