文字列線形DP +単調キュー最適化を生成します

ポータル

タイトル説明

正の整数n、x、yが与えられ、長さnの文字列を生成したい場合、2つの操作があります。

文字を追加するか、元の文字を削除します。コストはxです。
既存の文字列を1回(double)コピーして貼り付け、コストはyです。
最小コストを求めます。

分析

非常に単純な状態遷移方程式
F [I] =分(F [I-1] + X、F [I + 1] + y)が、
この問題に対処し、あなたが線形DPに行くことができない場合、明らかにループが存在し
、その後そしていつ削除する必要があるかを考える必要があります
。明らかに、文字列が長すぎる場合にのみ削除する必要があります。一部を削除してから2倍にする必要があるため、別の状態を書き込むことができます。伝達方程式

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

おすすめ

転載: blog.csdn.net/tlyzxc/article/details/112171956