[Educational Codeforces Round 16]E. Generate a String
试题描述
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 contents 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.
输入
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 parameters from the problem statement.
输出
输入示例
8 1 10
输出示例
8
数据规模及约定
见“输入”
题解
dp,设 f(i) 表示凑到 i 需要的最小花费,那么
1. i 为奇数,f(i) = min{ f(i-1) + x, f((i+1)/2) + y + x },注意到奇数不可能从某个数乘 2 得到。
2. i 为偶数,f(i) = min{ f(i-1) + x, f(i / 2) + y },注意到偶数不可能从奇数减 1 得到,否则不是最优的。
O(n) dp 一下就好了。
我的方法:
设 f(i, j) 表示凑到 i 用了 j 次删除的最小花费,则
1. i 为奇数 f(i, j) = min{ f(i-1, j) + x, f(i+1, j-1) + x }
2. i 为偶数 f(i, j) = min{ f(i-1, j) + x, f(i/2, j) + y, f(i+1, j-1) + x }
感觉减法最多不会超过 log(n) 次,所以 j 就只做到 log(n),时间复杂度是 O(nlogn) 的,需要开滚动数组。woc 这个算法在 cf 上居然 1996 ms 过了!
#include <iostream> #include <cstdio> #include <algorithm> #include <cmath> #include <stack> #include <vector> #include <queue> #include <cstring> #include <string> #include <map> #include <set> using namespace std; int read() { int x = 0, f = 1; char c = getchar(); while(!isdigit(c)){ if(c == '-') f = -1; c = getchar(); } while(isdigit(c)){ x = x * 10 + c - '0'; c = getchar(); } return x * f; } #define maxn 10000110 #define maxlog 25 #define LL long long int n, x, y, cur; LL f[maxn][2]; int main() { n = read(); x = read(); y = read(); for(int j = 0; j < 2; j++) for(int i = 1; i <= n + maxlog; i++) f[i][j] = (1ll << 60); LL ans = 1ll << 60; for(int j = 0; j < maxlog; j++, cur ^= 1) { for(int i = 1; i <= n + maxlog; i++) f[i][cur] = (1ll << 60); for(int i = 1; i <= n + maxlog; i++) { f[i][cur] = f[i-1][cur] + x; if(!(i & 1)) f[i][cur] = min(f[i][cur], f[i>>1][cur] + y); f[i][cur] = min(f[i][cur], f[i+1][cur^1] + x); // f[i][j] = min(min(f[i-1][j] + x, f[i>>1][j] + y), f[i+1][j-1] + x); if(i == n) ans = min(ans, f[i][cur]); // if(i == n) printf("%d %d %I64d ", i, j, f[i][cur]); } } printf("%I64d ", ans); return 0; }