题解:P9809 [SHOI2006] 作业 Homework
__Deng_Rui_Song__ · · 题解
preface
蒟蒻初学根号分治,写篇题解纪念一下。
problem
题目传送门。
solution
对于这道题,我们可以想到一种暴力做法:
-
将
X 直接插入集合中。 -
枚举
k 使得k\cdot Y\le3\times10^5 且k\ge0 ,将最优策略更新为集合中第一个大于等于k\cdot Y 的数,使用二分。
设值域大小为
-
枚举
k 使得1\le k\le3\times10^5 ,更新Y=k 的答案。 -
直接输出答案值。
设值域大小为
那到底怎么做呢?根号分治!(看前言就知道了)
根号分治,就好比把这两种暴力揉成一块(分块表兄),你管一半,我管另一半,那具体管那一半呢?我们设置一个阈值
更具体地说:
-
将
x 插入集合后,枚举k 使得k<B ,更新Y=k 的答案。 -
分为两种讨论:
-
设值域大小为
那么阈值
大家可以发现,其实根号分治重点在分治上而不是根号上。
code
:::warning[愣着干嘛?还不快写!就想 ctj 是吧!]
#include<bits/stdc++.h>
using namespace std;
const int B = sqrt(300000);
int n,ans[B];
set<int> st;
int main(){
memset(ans,0x3f,sizeof ans);
for (cin >> n; n--; ){
char c;
int x;
cin >> c >> x;
if (c == 'A'){
st.insert(x);
for (int i = 1; i < B; i++) ans[i] = min(ans[i],x % i);
}
else{
if (x < B) cout << ans[x] << '\n';
else{
int res = 1e9;
for (int i = 0; x * i <= 3e5; i++){
if (st.lower_bound(x * i) == st.end()) break;
res = min(res,*st.lower_bound(x * i) - x * i);
}
cout << res << '\n';
}
}
}
return 0;
}
:::