欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

CodeForces - 1409F Subsequences of Length Two(dp)

发布时间:2024/4/11 编程问答 41 豆豆
生活随笔 收集整理的这篇文章主要介绍了 CodeForces - 1409F Subsequences of Length Two(dp) 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

题目链接:点击查看

题目大意:给出一个字符串 s ,再给出一个长度为 2 的字符串 t ,最多可以进行 m 次操作,每次操作可以选择 s 中的一个字符修改为其他任意一个字符,问如何操作可以使得 t 作为子序列在 s 中的出现次数最多

题目分析:参考博客:https://www.cnblogs.com/qieqiemin/p/13619477.html

首先分析时间复杂度是 n^3 ,因为是有限制且无后效性的最优解问题,考虑 dp ,dp[ i ][ j ][ k ] 代表的是到了第 i 个位置时,用了 j 次操作,前面有 k 个 t[ 1 ] 时的最优解

考虑转移,显然对于 s 中的任意一个字符,要么不变,要么就是变为 t 中的字符是最优的,那么借助三个变量进行转移:

  • a :s[ i + 1 ] 与 t[ 1 ] 是否相等
  • b :s[ i + 1 ] 与 t[ 2 ] 是否相等
  • c :t[ 1 ] 与 t[ 2 ] 是否相等
  • 在第 i + 1 的位置 s[ i + 1 ] 不变:dp[ i + 1 ][ j ][ k + a ] = max( dp[ i + 1 ][ j ][ k + a ] , dp[ i ][ j ][ k ] + ( b ? k : 0 ) )
  • 在第 i + 1 的位置 s[ i + 1 ] 变为 t[ 1 ] :dp[ i + 1 ][ j + 1 ][ k + 1 ] = max( dp[ i + 1 ][ j + 1 ][ k + 1 ] , dp[ i ][ j ][ k ] + ( c ? k : 0 ) )
  • 在第 i + 1 的位置 s[ i + 1 ] 变为 t[ 2 ] :dp[ i + 1 ][ j + 1 ][ k + c ] = max( dp[ i + 1 ][ j + 1 ][ k + c ] , dp[ i ][ j ][ k ] + k )
  • 答案就是 dp[ n ][ j ][ k ] 中取最大值了,n 固定,j ∈ [ 0 , m ] ,k ∈ [ 0 , n ]

    考虑初始化:所有状态初始化为负无穷,dp[ 0 ][ 0 ][ 0 ] 初始化为 0 即可

    注意细节:因为是每次枚举的 i 向 i + 1 进行的转移,后面的两个方程只有在 j < m 时才能进行

    代码:
     

    #include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<climits> #include<queue> #include<map> #include<set> #include<sstream> #include<cassert> #include<bitset> using namespace std;typedef long long LL;typedef unsigned long long ull;const int inf=0x3f3f3f3f;const int N=210;char s[N],t[N];int dp[N][N][N];//dp[i][j][k]:到了第i个位置,花费了j次操作,有k个t[1]的最大贡献 int main() { #ifndef ONLINE_JUDGE // freopen("data.in.txt","r",stdin); // freopen("data.out.txt","w",stdout); #endif // ios::sync_with_stdio(false);memset(dp,-inf,sizeof(dp));int n,m;scanf("%d%d%s%s",&n,&m,s+1,t+1);dp[0][0][0]=0;for(int i=0;i<n;i++)for(int j=0;j<=m;j++)for(int k=0;k<=n;k++){int a=(s[i+1]==t[1]);int b=(s[i+1]==t[2]);int c=(t[1]==t[2]);dp[i+1][j][k+a]=max(dp[i+1][j][k+a],dp[i][j][k]+(b?k:0));//s[i]不变if(j<m){dp[i+1][j+1][k+1]=max(dp[i+1][j+1][k+1],dp[i][j][k]+(c?k:0));//s[i]->t[1]dp[i+1][j+1][k+c]=max(dp[i+1][j+1][k+c],dp[i][j][k]+k);//s[i]->t[2] }}int ans=0;for(int j=0;j<=m;j++)for(int k=0;k<=n;k++)ans=max(ans,dp[n][j][k]);printf("%d\n",ans);return 0; }

     

    总结

    以上是生活随笔为你收集整理的CodeForces - 1409F Subsequences of Length Two(dp)的全部内容,希望文章能够帮你解决所遇到的问题。

    如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。