首先我们先保证 ,然后发现先到达 的必然是 。
然后考虑操作,首先一开始答案设为 ,然后考虑调整 来做到能够除一个质因子,考虑枚举这个质因子,我们发现这些质因子肯定是从 里取,因为 ,所以我们记忆化搜索,设 表示 的情况下答案,调整的时候发现如果加减调整 到有枚举的相应质因数不同,则选择较小的,否则直接两个都跑,第二维不会超过 的约数个数,第一位因为不断地除上下取整,所以也不会太大,亲测最优解第 。
代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 1e6 + 5;
int T, a, b, c[N], s[N], cnt;
unordered_map <unsigned long long, int> f;
inline unsigned long long hs (const int i, const int j) {
return i * 1000000007ull + j;
}
int dfs (const int i, const int j) {
if (i == 0) return 1;
if (i == 1) return 0;
if (f.count(hs(i, j))) return f[hs(i, j)];
int ans = i - 1;
for (int k = 0; k < cnt; ++ k ) {
if (j % c[k] == 0) {
const int lst = i / c[k], nxt = (i + c[k] - 1) / c[k], X = j / c[k];
const int q = i - lst * c[k] + 1, h = nxt * c[k] - i + 1;
if (q < h) {
ans = min(ans, dfs (lst, X) + q);
} else if (h < q) {
ans = min(ans, dfs (nxt, X) + h);
} else {
ans = min(ans, dfs (lst, X) + q);
ans = min(ans, dfs (nxt, X) + h);
}
}
}
return f[hs(i, j)] = ans;
}
signed main() {
// system("fc gcd.out ans.out");
// freopen("gcd.in","r",stdin);
// freopen("gcd.out","w",stdout);
scanf("%d", &T);
while (T -- ) {
scanf("%d%d", &a, &b);
if (a > b) swap(a, b);
cnt = 0;
int x = b - a;
for (int i = 2; i * i <= x; ++ i ) {
if (x % i == 0) {
c[cnt] = i;
s[cnt] = 0;
while (x % i == 0) ++ s[cnt], x /= i;
++ cnt;
}
}
if (x > 1) c[cnt] = x, s[cnt] = 1, ++ cnt;
f.clear();
printf("%d\n", dfs (a, b - a));
}
return 0;
}