CodeForces 1096D(线性dp)

传送门

•题意

给出一个长度为n的字符串s,对于每个$s_{i}$有$a_{i}$的价值

让你删除最小的价值,使得字符串中不存在$hard$这个子序列

•思路

设dp[1]是不存在以$h$为前缀的最小代价

dp[2]是不存在以$ha$为前缀,也就是不存在$h$或者不存在$a$或者不存在$ha$的最小代价

同理,dp[3]是不存在以$har$为前缀的最小代价,dp[4]是不存在以$hard$为前缀的最小代价

dp[i]可以有dp[i-1]转移来,$dp[i]=min(dp[i]+a,dp[i-1])$

•代码

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 #define ll long long
 4 const int maxn=1e5+5;
 5 char s[maxn];
 6 ll dp[5];
 7 int main()
 8 {
 9     int n;
10     cin>>n;
11     scanf("%s",s+1);
12     for(int i=1;i<=n;i++)
13     {
14         ll x;
15         cin>>x;
16         if(s[i]=='h')
17             dp[1]+=x;
18         else if(s[i]=='a')
19             dp[2]=min(dp[2]+x,dp[1]);
20         else if(s[i]=='r')
21             dp[3]=min(dp[3]+x,dp[2]);
22         else if(s[i]=='d')
23             dp[4]=min(dp[4]+x,dp[3]);
24     }
25     cout<<dp[4]<<endl;
26 }
View Code

猜你喜欢

转载自www.cnblogs.com/MMMinoz/p/11493700.html