Codeforces 940E: Cashback Monotonic Queue Optimization DP

Portal

Title description

Give you a sequence of length n and integer c

You need to divide it into arbitrary segments

Assuming the length of each paragraph is k, remove the front ⌊ kc ⌋ \lfloor\frac{k}{c}\rfloorck⌋Small number

Minimize the sum of the remaining numbers

analysis

We can delete a minimum value from each interval of length k, or we can separate each number separately without deleting it, so it is easy to write the state equation
f[i] = min(f[i-1] + a[I],f[i-m] + sum[I]-sum[i-m]-min[i-m + 1 ~i])

The minimum value can be maintained with a monotonic queue or line segment tree

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 = 1e5 + 10;
int n,m;
ll a[N];
ll sum[N];
ll f[N];
struct node{
    
    
    int l,r;
    ll v;
}tr[N * 5];

void pushup(int u){
    
     //子节点信息更新父节点
    tr[u].v = min(tr[u << 1].v,tr[u << 1 | 1].v);
}

void build(int u,int l,int r){
    
    
    tr[u] = {
    
    l,r};
    if(l == r) {
    
    
        tr[u].v = a[l];
        return;
    }
    int mid = l + r >> 1;
    build(u << 1,l,mid),build(u << 1 | 1,mid + 1,r);
    pushup(u);
}

int query(int u,int l,int r){
    
    
    if(tr[u].l >= l && tr[u].r <= r) return tr[u].v;
    int mid = tr[u].l + tr[u].r >> 1;
    int v = INF;
    if(l <= mid) v = query(u << 1,l,r);
    if(r > mid) v = min(v,query(u << 1 | 1,l,r));
    return v;
}

int main(){
    
    
    scanf("%d%d",&n,&m);
    for(int i = 1;i <= n;i++) {
    
    
        scanf("%lld",&a[i]);
        sum[i] = sum[i - 1] + a[i];
    }
    build(1,1,n);
    for(int i = 1;i <= n;i++){
    
    
        f[i] = f[i - 1] + a[i];
        if(i < m)  continue;
        f[i] = min(f[i],f[i - m] + sum[i] - sum[i - m] - query(1,i - m + 1,i));

    }
    printf("%lld\n",f[n]);
    return 0;
}

/**
*  ┏┓   ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃       ┃
* ┃   ━   ┃ ++ + + +
*  ████━████+
*  ◥██◤ ◥██◤ +
* ┃   ┻   ┃
* ┃       ┃ + +
* ┗━┓   ┏━┛
*   ┃   ┃ + + + +Code is far away from  
*   ┃   ┃ + bug with the animal protecting
*   ┃    ┗━━━┓ 神兽保佑,代码无bug 
*   ┃        ┣┓
*    ┃        ┏┛
*     ┗┓┓┏━┳┓┏┛ + + + +
*    ┃┫┫ ┃┫┫
*    ┗┻┛ ┗┻┛+ + + +
*/

Guess you like

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