【入门dp】E - Generate a String(字符串复制增加删除)
Description
zscoder wants to generate an input file for some programming competition problem.
His input is a string consisting of n letters 'a'. He is too lazy to write a generator so he will manually generate the input in a text editor.
Initially, the text editor is empty. It takes him x seconds to insert or delete a letter 'a' from the text file and y seconds to copy the conte
nts of the entire text file, and duplicate it.
zscoder wants to find the minimum amount of time needed for him to create the input file of exactly n letters 'a'. Help him to determine
the amount of time needed to generate the input.
Input
The only line contains three integers n, x and y (1 ≤ n ≤ 107, 1 ≤ x, y ≤ 109) — the number of letters 'a' in the input file and the paramete
rs from the problem statement.
Output
Print the only integer t — the minimum amount of time needed to generate the input file.
Sample Input
8 1 1
4
8 1 10
8
题意:要输入n个字符'a',有两种操作,一种是输入或删除一个'a',耗时x;另一种是把当前的整个文本复制粘贴,耗时y。求最少时间。
思路:每个长度都有几种方法得到:偶数--可以是他的一半复制得到,或者他前面的那个+1得到
奇数--可以是他的一半复制再+1得到,或者他的一半+1复制再-1得到,或者他前面的+1得到
这种分段的,求最优的,有规律可循的就用dp
代码:
#include <iostream> #include <cstring> #include <string> #include <cstdio> #include <cmath> using namespace std; int MAX=10000005; int main() { long long n,m,k,x,y,i; long long dp[MAX]; scanf("%lld %lld %lld",&n,&x,&y); dp[1]=x; for(i=2;i<=n;i++) { if(i%2!=0) { dp[i]=min(dp[i-1]+x,min(dp[i/2]+x+y,dp[i/2+1]+x+y)); } else { dp[i]=min(dp[i-1]+x,dp[i/2]+y); } } printf("%lld\n",dp[n]); return 0; }