ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

C - String Game

2021-05-30 10:00:17  阅读:280  来源: 互联网

标签:String int Game dp 字符串 Bob Clair string


 

题目

Clair and Bob play a game.Clair writes a string of lowercase characters, in which Bob sets the puzzle by selecting one of his favorite subsequence as the key word of the game. But Bob was so stupid that he might get some letters wrong.

Now Clair wants to know whether Bob’s string is a subsequence of Clair’s string. and how many times does Bob’s string appear as a subsequence in Clair’s string. As the answer maybe too large, you should output the answer modulo 109+7.

Input

The input may contain multiple test cases.

Each test case contains exactly two lines. 
The first line is Clair’s string, and the second line is Bob’s string. 
The length of both strings are no more than 5000.

 Output

For each test case, output one line, including a single integer representing how many times Bob’s string appears as a subsequence in Clair’s string.
The answer should modulo 109+7.

 Sample Input

eeettt
et
eeettt
te

 Sample Output

9
0
1
2


题意+翻译:

Clair和Bob玩了一个游戏。Clair写了一串小写字母,Bob通过选择一个他最喜欢的子序列作为游戏的关键字来设置谜题。
但是Bob太笨了,他可能把一些字母搞错了。
现在Clair想知道Bob的字符串是否是Clair的字符串的子序列。以及Bob的字符串作为Clair的字符串的子序列出现了多少次。
但是因为答案可能太大了,应该输出对(10的9次方+7)取模的结果。

输入样例:

输入可能包含多个测试用例。
每个测试用例包含两行。第一行是Clair的字符串,第二行是Bob的字符串。两个字符串的长度不超过5000


输出样例:

对于每个测试用例,输出一行,包括一个整数,表示Bob的字符串作为Clair的字符串的**子序列出现的次数**。
答案应该是对(10的9次方+7)取模。


解题思路

目的:给定字符串A 和字符串B 问B在A中子序列的出现次数

一开始我们想要使用遍历去计算子字符串出现的次数,就是按顺序一个一个的进行计算,后面发现计算量特别的大,于是后来使用动态规划这个算法

算法:动态规划
思路:

用dp计数,其中dp[i][j]代表着子字符串中前i个字母在长字符串的前j出现次数数
每次dp[i][j]=dp[i-1][j]继承过来
当a[i]==b[j]的时候 dp[i][j]+=dp[i-1][j-1] 所有的 dp[i][0]=1

代码实现

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e3+10;
const int mod=1e9+7;
int dp[maxn*5][maxn];
int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    string a,b;
    while(cin>>a>>b)
    {
        memset(dp,0,sizeof(dp));
        int n=a.size(),m=b.size();
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=m;j++)
            {
                dp[i][j]=dp[i-1][j];
                if(a[i-1]==b[j-1])
                {
                    if(j==1)
                        dp[i][j]++;
                    else
                        dp[i][j]+=dp[i-1][j-1];
                }
                dp[i][j]%=mod;
            }
        }
        cout<<dp[n][m]<<endl;
    }
}

 

标签:String,int,Game,dp,字符串,Bob,Clair,string
来源: https://blog.csdn.net/m0_56333251/article/details/117394522

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有