Bootstrap

CF 57 (Div. 2) D. Easy Problem (Dynamic Programming)

D. Easy Problem

题目链接:

题意

给你一个长度为N的串,如果里面出现了"hard"这个子序列,那么这个串就是hard串,你可以删除一些字符,来使他不是一个hard串,每个字符会有一个权值A[i],每次删除字符,都会消耗权值,要求最小的删除方案是什么?


思路

官方题解

Denote string t as hard.

We will solve this problem with dynamic programming.

Denote dpcnt,len — the minimum possible ambiguity if we considered first cnt letters of statement and got prefix t having length len as a subsequence of the string.

If cnt-th letter of the statement is not equal to tlen, then d p c n t , l e n = d p c n t − 1 , l e n dp_{cnt,len}=dp_{cnt−1,len} dpcnt,len=dpcnt1,len — we don’t have to change it.

Otherwise we either change the letter, or let it stay as it is (and the length of the prefix we found so far increases): d p c n t , l e n = m i n ( d p c n t − 1 , l e n − 1 , d p c n t − 1 , l e n + a c n t − 1 ) . dp_{cnt,len}=min(dp_{cnt−1,len−1},dp_{cnt−1,len+acnt−1}). dpcnt,len=min(dpcnt1,len1,dpcnt1,len+acnt1).

dp[i][0/1/2/3]表示使前i位不含h/ha/har/hard子序列的最小代价


代码

#include<bits/stdc++.h>
using namespace std;
#define rep(i,j,k) for(int i = (int)j;i <= (int)k;i ++)
#define debug(x) cerr<<#x<<":"<<x<<endl
#define pb push_back

typedef long long ll;
const int MAXN = 1e6+7;
const ll INF = (ll)1e18+7;

char str[MAXN];
int A[MAXN];
ll dp[MAXN][4]; 
//dp[i][0]/[1]/[2]/[3] standfor the minimum cost for the h/ha/har/hard not disappear

int main()
{
    ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);

    int N;
    cin >> N;
    cin >> str+1;
    rep(i,1,N) cin >> A[i];
    rep(i,1,N) rep(j,0,3) dp[i][j] = INF;
    rep(i,1,N) {
        if (str[i] == 'h') dp[i][0] = dp[i-1][0] + A[i];
        else               dp[i][0] = dp[i-1][0];
        if (str[i] == 'a') dp[i][1] = min(dp[i-1][0],dp[i-1][1] + A[i]);
        else               dp[i][1] = dp[i-1][1];
        if (str[i] == 'r') dp[i][2] = min(dp[i-1][1],dp[i-1][2] + A[i]);
        else               dp[i][2] = dp[i-1][2];
        if (str[i] == 'd') dp[i][3] = min(dp[i-1][2],dp[i-1][3] + A[i]);
        else               dp[i][3] = dp[i-1][3];
        //debug(dp[i][3]);
    }
    cout << dp[N][3] << endl;

}

;