Codeforces-710E Generate a String

题目大意:

有三个操作,插入删除和复制。其中插入和删除均耗费x时间来插入或删除一个字符,复制耗费y时间将当前文件内所有字符复制并粘贴(就是字符*2),现在需要生成n个字符,问你最少需要的时间。

解题思路:

DP

dp[i]表示生成i个字符需要的最少时间,那么状态转移方程就是

dp[i] = min(dp[i-1] + x, dp[i+1] + x, dp[i / 2] + y);

代码写起来会有些细节修改,所以xjb写吧。

代码:

#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
const LL INF = 1e18;
const int maxn = 1e7 + 5;
LL dp[maxn << 1];
int main() {
	int n, x, y;
	cin >> n >> x >> y;
	fill(dp + 1, dp + 1 + 2 * n, INF);
	dp[0] = 0;
	for (int i = 1; i <= n; ++i) {
		if (i & 1) {
			dp[i] = min(dp[i - 1], dp[i + 1]) + x;
			dp[i << 1] = min(dp[i << 1], dp[i] + y);
		} else {
			dp[i] = min(dp[i-1] + x, dp[i >> 1] + y);
			dp[i << 1] = min(dp[i << 1], dp[i] + y);
		}
	}
	cout << dp[n] << endl;
	return 0;
}


原文地址:https://www.cnblogs.com/wiklvrain/p/8179368.html