传送门
题目描述
给定正整数 n, x, y,你要生成一个长度为 n 的字符串,有两种操作:
添一字符或删去一个原有字符,代价为 x;
将已有字串复制粘贴一次(翻倍),代价为 y。
求最小代价。
分析
一个很简单的状态转移方程
f[i] = min(f[i - 1] + x,f[i + 1] + y);
但是很显然这样处理这个问题就有了环,不能去线性dp
然后我们需要思考什么时候需要去进行删除操作
很显然,只有当我们的字符串过长,需要去删减一部分然后去采取翻倍操作的时候才需要进行删减操作,所以我们可以写出另一个状态转移方程
f[i] = min(f[i - 1] + x,f[k] + y + (k * 2 - i) * x);
然后就会发现,这其实是一个单调队列优化的线性dp问题
代码
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <cstring>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define _CRT_SECURE_NO_WARNINGS
#pragma GCC optimize("Ofast","unroll-loops","omit-frame-pointer","inline")
#pragma GCC option("arch=native","tune=native","no-zero-upper")
#pragma GCC target("avx2")
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
const int INF = 0x3f3f3f3f;
const int N = 1e7 + 10;
ll f[N],q[N];
ll n,x,y;
int main(){
scanf("%lld%lld%lld",&n,&x,&y);
int hh = 1,tt = 0;
for(ll i = 1;i <= n;i++){
while(hh <= tt && hh * 2 < i) ++hh;
f[i] = f[i - 1] + x;
if(hh <= tt) f[i] = min(f[i],f[q[hh]] + y + (q[hh] * 2 - i) * x);
while(hh <= tt && f[q[tt]] + q[ tt ] * 2ll * x >= f[i] + i * 2ll * x) tt--;
q[++tt] = i;
}
printf("%lld\n",f[n]);
}
/**
* ┏┓ ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃ ┃
* ┃ ━ ┃ ++ + + +
* ████━████+
* ◥██◤ ◥██◤ +
* ┃ ┻ ┃
* ┃ ┃ + +
* ┗━┓ ┏━┛
* ┃ ┃ + + + +Code is far away from
* ┃ ┃ + bug with the animal protecting
* ┃ ┗━━━┓ 神兽保佑,代码无bug
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛ + + + +
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛+ + + +
*/