题意:构造一个由a组成的串,如果插入或删除一个a,花费时间x,如果使当前串长度加倍,花费时间y,问要构造一个长度为n的串,最少花费多长时间。
分析:dp[i]---构造长度为i的串需要花费的最短时间。
1、构造长度为1的串,只能插入,dp[1] = x。
2、当前串的长度i为偶数,可以
(1)长度为i/2的串加倍:dp[i / 2] + y
(2)长度为i-1的串插入一个a:dp[i - 1] + x
3、当前串的长度i为奇数,可以
(1)长度为i/2的串加倍,再加上一个a:dp[i / 2] + y + x
(2)长度为i/2+1的串加倍,再删除一个a:dp[i / 2 + 1] + y + x
(3)长度为i-1的串插入一个a:dp[i - 1] + x
#include<cstdio> #include<cstring> #include<cstdlib> #include<cctype> #include<cmath> #include<iostream> #include<sstream> #include<iterator> #include<algorithm> #include<string> #include<vector> #include<set> #include<map> #include<stack> #include<deque> #include<queue> #include<list> #define lowbit(x) (x & (-x)) const double eps = 1e-8; inline int dcmp(double a, double b){ if(fabs(a - b) < eps) return 0; return a > b ? 1 : -1; } typedef long long LL; typedef unsigned long long ULL; const int INT_INF = 0x3f3f3f3f; const int INT_M_INF = 0x7f7f7f7f; const LL LL_INF = 0x3f3f3f3f3f3f3f3f; const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f; const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1}; const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1}; const int MOD = 1e9 + 7; const double pi = acos(-1.0); const int MAXN = 1e7 + 10; const int MAXT = 10000 + 10; using namespace std; LL dp[MAXN]; int main(){ LL n, x, y; scanf("%lld%lld%lld", &n, &x, &y); memset(dp, LL_INF, sizeof dp); dp[1] = x; for(LL i = 2; i <= n; ++i){ if(i % 2 == 0){ dp[i] = min(dp[i / 2] + y, dp[i - 1] + x); } else{ dp[i] = min(dp[i / 2] + x + y, dp[i - 1] + x); dp[i] = min(dp[i], dp[i / 2 + 1] + y + x); } } printf("%lld ", dp[n]); return 0; }