[題解]AT_abc288_e [ABC288E] Wish List

WaterSunHB發表於2024-06-23

思路

定義 \(dp_{i,j}\) 表示在標號前 \(i\) 個商品中,將所有 \(x_k \leq i\) 的商品購買,且一共買了 \(j\) 件商品的花費最小值。

那麼,對於 \(i\) 號商品就會有 選/不選,兩種狀態:

  1. 如果選,那麼有 \(dp_{i,j} = \min(dp_{i - 1,j - 1} + \min_{k = i - j + 1}^i(c_k) + a_i)\)。因為對於 \(i\) 號商品,如果第一次選擇購買 \(i\) 號商品,貢獻為 \(c_i + a_i\);如果最後一次選擇購買 \(i\) 號商品,貢獻為 \(c_{i - j + 1} + a_i\)。那麼,對於第 \(i\) 件商品,貢獻最少的就是 \(\min_{k = i - 1 + 1}^i(c_k) + a_i\)
  2. 如果不選,那麼有 \(dp_{i,j} = \min(dp_{i - 1,j})\)

這裡最小值,我用的是 ST 表預處理。

Code

#include <bits/stdc++.h>  
#define int long long  
#define re register  
  
using namespace std;  
  
const int N = 5010,M = 20,inf = 0x3f3f3f3f3f3f3f3f;  
int n,m,ans = inf;  
int lg[N],arr[N];  
int dp[N][N];  
bool st[N];  
  
struct RMQ_ST{  
    #define pot(x) (1 << x)  
  
    int dp[N][M];  
  
    inline void init(){  
        lg[1] = 0;  
        for (re int i = 2;i <= n;i++) lg[i] = lg[i / 2] + 1;  
        for (re int j = 1;j <= lg[n];j++){  
            for (re int i = 1;i <= n - pot(j) + 1;i++) dp[i][j] = min(dp[i][j - 1],dp[i + pot(j - 1)][j - 1]);  
        }  
    }  
  
    inline int query(int l,int r){  
        int x = lg[r - l + 1];  
        return min(dp[l][x],dp[r - pot(x) + 1][x]);  
    }  
  
    #undef pot  
}ST;  
  
inline int read(){  
    int r = 0,w = 1;  
    char c = getchar();  
    while (c < '0' || c > '9'){  
        if (c == '-') w = -1;  
        c = getchar();  
    }  
    while (c >= '0' && c <= '9'){  
        r = (r << 3) + (r << 1) + (c ^ 48);  
        c = getchar();  
    }  
    return r * w;  
}  
  
signed main(){  
    memset(dp,inf,sizeof(dp));  
    dp[0][0] = 0;  
    n = read();  
    m = read();  
    for (re int i = 1;i <= n;i++) arr[i] = read();  
    for (re int i = 1;i <= n;i++) ST.dp[i][0] = read();  
    for (re int i = 1;i <= m;i++){  
        int x;  
        x = read();  
        st[x] = true;  
    }  
    ST.init();  
    for (re int i = 1;i <= n;i++){  
        for (re int j = 1;j <= i;j++) dp[i][j] = min(dp[i][j],dp[i - 1][j - 1] + ST.query(i - j + 1,i) + arr[i]);  
        if (st[i]) continue;//如果 st[i] = true 表示 i 必選,所以下面對於 i 商品不選的情況跳過   
        for (re int j = 0;j <= i;j++) dp[i][j] = min(dp[i][j],dp[i - 1][j]);  
    }  
    for (re int i = m;i <= n;i++) ans = min(ans,dp[n][i]);  
    printf("%lld",ans);  
    return 0;  
}  

相關文章