题意及思路:https://blog.csdn.net/bossup/article/details/37076965
代码:
#include <bits/stdc++.h> #define LL long long #define INF 1e18 using namespace std; int lcm(int x, int y) { return x * y / __gcd(x, y); } const int maxn = 500010; LL a, b, k; LL dp[maxn]; unordered_map<LL, bool> v; queue<pair<LL, LL> > q; LL bfs(LL x, LL y) { q.push(make_pair(x, 0)); while(!q.empty()) { pair<LL, LL> tmp = q.front(); q.pop(); if(v[tmp.first]) continue; v[tmp.first] = true; if(tmp.first == y) return tmp.second; for (int i = 2; i <= k; i++) { if(tmp.first % i != 0) { q.push(make_pair(tmp.first - tmp.first % i, tmp.second + 1)); } } q.push(make_pair(tmp.first - 1, tmp.second + 1)); } } LL dfs(LL x) { if(dp[x] != -1) return dp[x]; LL tmp = INF; for (int i = 2; i <= k; i++) { if(x % i != 0) tmp = min(tmp, dfs(x - x % i)); } tmp = min(tmp, dfs(x - 1)); return dp[x] = tmp + 1; } int main() { int LCM = 1; scanf("%lld%lld%d", &a, &b, &k); for (int i = 2; i <= k; i++) { LCM = lcm(LCM, i); } memset(dp, -1, sizeof(dp)); dp[0] = 0; for (int i = 1; i < LCM; i++) { dfs(i); } LL ans = 0; if(a - a % LCM >= b) { ans += dp[a % LCM]; a -= a % LCM; } LL del = a - b; LL tmp = del / LCM; a -= tmp * LCM; ans += tmp * (dp[LCM - 1] + 1); if(a > b) { LL tmp = bfs(a, b); ans += tmp; } printf("%lld ", ans); }