Generate a String linear DP + monotonic queue optimization

Portal

Title description

Given a positive integer n, x, y, you want to generate a string of length n, there are two operations:

Add a character or delete an original character, the cost is x;
copy and paste an existing string once (double), and the cost is y.
Seek the minimum cost.

analysis

A very simple state transition equation
f[i] = min(f[i-1] + x, f[i + 1] + y);
but obviously there is a loop when dealing with this problem, and you cannot go to linear dp
and then We need to think about when we need to delete
it. Obviously, we need to delete it only when our string is too long, we need to delete a part and then double it, so we can write another state Transfer equation

f [i] = min (f [i - 1] + x, f [k] + y + (k * 2 - i) * x);

Then you will find that this is actually a linear dp problem of monotonic queue optimization

Code

#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 
*   ┃        ┣┓
*    ┃        ┏┛
*     ┗┓┓┏━┳┓┏┛ + + + +
*    ┃┫┫ ┃┫┫
*    ┗┻┛ ┗┻┛+ + + +
*/

Guess you like

Origin blog.csdn.net/tlyzxc/article/details/112171956