D. Easy Problem(简单DP)

本文解析了CodeForces竞赛中一道关于字符串处理的问题,通过动态规划算法计算删除字符串中所有'hard'子串的最小成本。介绍了算法思路与AC代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:http://codeforces.com/contest/1096/problem/D

题目大意:给你一个字符串,然后再给你去掉每个字符串的每个字符的花费,然后问你使得字符中不再存在hard这个单词,可以是不连续的。

 具体思路:我们从头开始,非hard的单词就不需要考虑了,然后考虑一下,当遇到a的时候,我们就考虑构成h的最小花费,当遇到har的时候,我们就考虑构成ha的最小花费,当遇到hard的时候,我们就考虑构成hard的最小花费就可以了。

 AC代码:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5+10;
# define inf 1ll<<60
# define ll long long
ll dp[5][maxn],cost[maxn];
char f[5]= {"hard"};
string str;
ll n;
ll cal(int t1,int t2)
{
    if(t1==4)
        return inf;
    if(t2==n)
        return 0;
    if(dp[t1][t2]!=-1)
        return dp[t1][t2];
    if( str[t2] == f[t1])
    {
        dp[t1][t2] =min( cal(t1+1,t2+1), cal(t1,t2+1)+cost[t2]);
    }
    else
    {
        dp[t1][t2] =cal(t1,t2+1);
    }
    return dp[t1][t2];
}
int main()
{
    cin>>n;
    cin>>str;
    for(int i=0; i<n; i++)
    {
        cin>>cost[i];
    }
//    for(int i=0;i<4;i++){
//    cout<<f[i]<<endl;
//    }
    memset(dp,-1,sizeof(dp));
    cout<<cal(0,0)<<endl;
    return 0;
}

 

ac代码B. Normal Problem思路ac代码C. Hard Problem思路ac代码D. Harder Problem思路ac代码TIPSD. Harder Problem (Plus)思路代码A. Easy Problem思路控制第一位都遍历即可。ac代码#include<bits/stdc++.h>using namespace std; int main() { int t; cin >> t; while (t--) { int n; cin >> n; cout<<n-1<<endl; } return 0;}B. Normal Problem思路把'p'和'q'倒过来即可,然后倒序输出。ac代码#include<bits/stdc++.h>using namespace std; const int N=110; int main() { int t; cin >> t; while (t--) { char a[N]; cin >> a; for(int i = 0;i<strlen(a);i++){ if(a[i]=='q') a[i]='p'; else if(a[i]=='p') a[i]='q'; } for(int i = strlen(a)-1;i>=0;i--){ cout<<a[i]; } cout<<endl; } return 0;}C. Hard Problemproblem C思路先确定一定要坐在两排的猴,再处理可移动位置的猴。思路一定要清晰!ac代码#include<bits/stdc++.h>using namespace std; const int N=110; int main() { int t; cin >> t; while (t--) { int m,a,b,c; cin >> m>>a>>b>>c; int ans=0; if(a>m) ans+=m; else ans+=a; if(b>m) ans+=m; else ans+=b; if(2*m-ans>0&&c-(2*m-ans)>0) ans+=2*m-ans; else if(2*m-ans>0&&c-(2*m-ans)<=0) ans+=c; cout<<ans<<endl; } return 0;}D. Harder Problemproblem D思路就是每个值都出现一遍,就可以保证大家都是众数都有效。在输入时就检测如果这个数没出现过那么先把这个数存到数组里,数组的数全部存完,再把没存过的挨个存一遍进去,能保证在所需要的众数出现及之前就在新数组存过该数。ac代码#include<bits/stdc++.h>using namespace std; const int N=2e5+10; int main() { int t; cin >> t; while (t--) { int n; cin >> n; int a[N],cnt[N]={0},b[N]={0},j=1; for(int i=1;i<=n;i++){ cin>>a[i]; if(cnt[a[i]]==0) { cnt[a[i]]++; b[j++]=a[i];
最新发布
04-06
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值