Solution
这里提供一种根号分治的做法。
记答案为 ,显然,我们有 。这是因为满足 的最小的 小于 。
对 的大小进行分类讨论:
-
当 时,直接枚举 即可,复杂度 。
-
当 时,不难发现 。记 ,,那么 取 时, 。
证明:
若 ,则 。
于是我们得到:
所以 。也就是说, 此时取的不是最优值。
综上,我们只需要枚举 即可。复杂度 。
于是这道题就以 的复杂度做完了。
Code
#include <cstdio>
#include <cmath>
#include <algorithm>
int T, a, b, s, ans;
int udiv(const int x, const int y) {return (x + y - 1) / y;}
int main() {
scanf("%d", &T);
while(T--) {
scanf("%d %d", &a, &b);
if(a >= b) { // 记得特判 a >= b 的情况
printf("%d\n", a - b);
continue;
}
s = sqrt(b); ans = std::min(b - a, ((a - b) % a + a) % a);
if(a <= s) { // 分类讨论
for(int i = 1; i <= a; i++) {
int x = a + i;
ans = std::min(ans, i + ((x - b) % x + x) % x);
}
} else {
for(int i = 2; i <= a; i++) {
int x = udiv(b, i);
if(x < a) break; // 本质上,这个边界特判和上述的差不多
ans = std::min(ans, x - a + ((x - b) % x + x) % x);
}
}
printf("%d\n", ans);
}
return 0;
}