跳到正文

题解

题解:CF2114F Small Operations

lly66666约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年8月15日
收录
2025年12月12日
更新
2026年11月11日
篇幅
约 2 分钟
题目
CF2114F

版本

  1. v1当前

解析:

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

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

然后进行记忆化搜索:

初始化:

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

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

C++
dfs(tx) + dfs(ty)

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

C++
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;//记忆化
}

最终代码:

C++
#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;
}

完结撒花!

原文