Educational Codeforces Round 16 E. Generate a String (dp)

来源:互联网 发布:qq活动抽奖软件 编辑:程序博客网 时间:2024/05/29 18:21

链接

E. Generate a String


题意

需要你得到一个长度为n的由a字符组成的串,起初串为空,添加/删除一个a字符消耗为x,将目前的序列长度翻倍的消耗为y,求长度为n时的最小消耗。


思路

起初串为空,得到长度为1的串,最小消耗一定是x。
对2~n的长度,如果k为奇数,则d[k] = min(d[k-1] + x, d[(k+1)/2 + x + y]),如果k为偶数,则d[k] = min(d[k-1] + x, d[k/2] + y)。
另外注意一下范围,要用long long。

感觉上这样的确是对的,但是证明不了。试证过好几次,觉得有一种“是先有鸡还是先有蛋”的感觉。如果有谁能给出证明还请告知。


代码

#include <cstdio>#include <iostream>using namespace std;typedef long long lint;#define maxn (10000010)lint d[maxn];int main(){    int n, x, y;    cin >> n >> x >> y;    d[1] = x;    for(int i = 2; i <= n; i++)    {        d[i] = d[i - 1] + x;        if(i % 2) d[i] = min(d[i], d[(i + 1) / 2] + x + y);        else d[i] = min(d[i], d[i / 2] + y);    }    cout << d[n] << endl;    return 0;}
0 0