1 solutions
-
-2
题意解释
给定一个正整数 ,将 表示为一些只包含 的数字之和,使得这些数字的长度之和尽量小。
只包含 的数字,指的是形如的数字,或其相反数。
知识点提炼
搜索,剪枝
核心解题思路
思路一:
用 表示 写作十进制数字的长度。令 表示包含 个的整数。
注意到:我们使用的数字长度不会超过,考虑正负,至多只有 个可选的数字。
用 表示凑出数字 最少需要的数字长度和。那么有转移。
用最短路更新 即可,在求最短路过程中,超过的状态可以直接舍弃,并且
复杂度 。
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { ios::sync_with_stdio(false); cin.tie(0); ll n; cin >> n; priority_queue<pair<ll, ll>, vector<pair<ll, ll>>, greater<>> q; map<ll, ll> dis; q.push({dis[0] = 0, 0}); while (!q.empty()) { auto [w, u] = q.top(); q.pop(); if (u == n) { cout << w << endl; break; } if (dis[u] != w) continue; for (ll x = 1, i = 1; x <= n * 10 + 1; x = x * 10 + 1, i++) { for (auto o : set<int>{-1, 1}) { ll to = abs(u + x * o); if (to > 10 * n) continue; if (!dis.count(to) || dis[to] > w + i) { dis[to] = w + i; q.push({dis[to], to}); } } } } return 0; }思路二:
考虑一种贪心的思路。
假设我们使用了 个 ,代价为,那么我们将其替换成一个和一个,代价是,一定是更优的。
所以可以考虑从高位开始逐位贪心。对于第 位,我们要使用若干个 ,使得 。不妨设,那么只有两种选择
-
减去 个
-
减去 个
如果使用更多或者更少的,那么我们只能用凑出一个,由上述分析可知代价一定会变差。
因此每一位只有两种选择,复杂度 ,期望得分 分。
#include <bits/stdc++.h> using namespace std; typedef long long ll; vector<ll> x; ll dfs(int p, ll n) { if (p < 0) return 0; ll L = dfs(p - 1, n % x[p]) + (n / x[p]) * (p + 1); ll R = dfs(p - 1, abs(n % x[p] - x[p]) % x[p]) + (n / x[p] + (n % x[p] != 0)) * (p + 1); return min(L, R); } int main() { ios::sync_with_stdio(false); cin.tie(0); ll n; cin >> n; x.push_back(1); for (int i = 1; i < 17; i++) x.push_back(x.back() * 10 + 1); cout << dfs(16, n) << endl; }本题易错点
- 贪心分析时,容易忽略可以减成负数的情况
-
- 1
Information
- ID
- 98
- Time
- 500ms
- Memory
- 128MiB
- Difficulty
- 7
- Tags
- (None)
- # Submissions
- 21
- Accepted
- 8
- Uploaded By