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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章