CodeForces 710E Generate a String (DP)

时间:2023-03-09 05:10:51
CodeForces 710E  Generate a String (DP)

题意:给定 n,x,y,表示你要建立一个长度为 n的字符串,如果你加一个字符要花费 x时间,如果你复制前面的字符要花费y时间,问你最小时间。

析:这个题,很明显的DP,dp[i]表示长度为 i 的字符串的最少花费,当 i 是偶数时,要么再加一个字符,要么从i/2中复制,如果为奇数,要么再加1个字符,

要么从i/2先加一个,再复制。即:

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

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

代码如下:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <cstdio>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <cstring>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
#include <cctype>
#include <stack>
#define freopenr freopen("in.txt", "r", stdin)
#define freopenw freopen("out.txt", "w", stdout)
using namespace std; typedef long long LL;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const LL LNF = 100000000000000000;
const double inf = 0x3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-8;
const int maxn = 1e7 + 5;
const int mod = 1e9 + 7;
const char *mark = "+-*";
const int dr[] = {-1, 0, 1, 0};
const int dc[] = {0, 1, 0, -1};
int n, m;
inline bool is_in(int r, int c){
return r >= 0 && r < n && c >= 0 && c < m;
}
inline LL Max(LL a, LL b){ return a < b ? b : a; }
inline LL Min(LL a, LL b){ return a > b ? b : a; }
inline int Max(int a, int b){ return a < b ? b : a; }
inline int Min(int a, int b){ return a > b ? b : a; }
LL dp[maxn]; int main(){
LL x, y;
while(scanf("%d", &n) == 1){
scanf("%I64d %I64d", &x, &y);
memset(dp, 0, sizeof dp);
dp[1] = x;
for(int i = 2; i <= n; ++i){
if(i & 1){
dp[i] = min(dp[i-1]+x, dp[i/2+1]+y+x);
}
else{
dp[i] = min(dp[i-1]+x, dp[i/2]+y);
}
}
printf("%I64d\n", dp[n]);
}
return 0;
}