【发布时间】:2018-06-19 10:09:56
【问题描述】:
我最近遇到了这个问题:
在挑战中,给你一个包含 n 个数字和一个整数 k 的数组。在一分钟内,您可以将数组的任何元素更改为您想要的任何整数。找出满足以下条件的最少时间:对于所有 i 从到 1,n - 1,a[i] - a[i - 1] = k。由于 n, k
我贪婪地意识到这个问题可能是DP,但我找不到答案。这个topic 类似,但那里的答案没有用(在我看来)。我只是在寻找一个伪(或 cpp)代码。
UPD:我在 O(n^2) 中编写了一个蛮力解决方案,如果它对您有帮助,这里是代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pi;
typedef pair<ll, ll> pl;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<double> vd;
typedef vector<bool> vb;
typedef vector<char> vc;
typedef vector<string> vs;
typedef vector<pi> vp;
typedef vector<pl> vpl;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cerr.tie(nullptr);
int n, k;
cin >> n >> k;
vi a(n);
for (auto& i : a)
cin >> i;
int res = INT32_MAX;
for (int i = 0; i < n; ++i){
int s = a[i], sol = 0;
for (int j = i + 1; j < n; ++j){
s += k;
if (a[j] != s)
++sol;
}
s = a[i];
for (int j = i - 1; j > -1; --j){
s -= k;
if (a[j] != s)
++sol;
}
res = min(sol, res);
}
cout << res << '\n';
}
【问题讨论】:
-
您是否尝试过自己将动态规划应用到这个问题上?您具体在哪里对此有疑问?这里的人更有可能帮助在问题中表现出实际努力的人。
-
@SergGr 我的尝试完全错误。我认为这对任何人都没有帮助,而是我在 UPD 中给予了蛮力。
-
在类似的主题 stackoverflow.com/questions/50922702 我已被警告问题来自正在进行的比赛
-
哦,我不知道。我应该删除我的答案吗?现在感觉有点晚了。
-
@Qubit 是的,你应该在比赛结束前删除你的答案。