题解:CF2114F Small Operations

· · 题解

解析:

在读入 x 和 y 后先同时除以他们的最大公约数:

cin >> x >> y >> k;
int gcd = __gcd(x, y), tx = x / gcd, ty = y / gcd;

然后进行记忆化搜索:

初始化:

memset(dp, -1, sizeof(dp));
dp[1] = 0;

然后定义 dfs,最终的结果就为:

dfs(tx) + dfs(ty)

dfs 也很简单,直接上代码:

int dfs(int x) {
    if(dp[x] != -1) return dp[x]; //返回
    int res = 0x3f3f3f3f;
    for(int i = 2; i <= k; i ++) {
        if(x == i) { //可以直接除尽
            res = 1;
            break;
        }
        if(x % i == 0) res = min(res, dfs(x / i) + 1); // “货比三家”
    }
    return dp[x] = res;//记忆化
}

最终代码:

#include <bits/stdc++.h>
using namespace std;
int x, y, k, t, dp[1000001];
int dfs(int x) {
    if(dp[x] != -1) return dp[x];
    int res = 0x3f3f3f3f;
    for(int i = 2; i <= k; i ++) {
        if(x == i) {
            res = 1;
            break;
        }
        if(x % i == 0) res = min(res, dfs(x / i) + 1);
    }
    return dp[x] = res;
}
signed main() {
    cin >> t;
    while(t --) {
        cin >> x >> y >> k;
        int gcd = __gcd(x, y), tx = x / gcd, ty = y / gcd;
        memset(dp, -1, sizeof(dp));
        dp[1] = 0;
        int cnt = dfs(tx) + dfs(ty);
        if(cnt > 1e9) cout << -1 << endl;
        else cout << cnt << endl;
    }
    return 0;
}

完结撒花!