1. 程式人生 > 其它 >寒假演算法題練習4

寒假演算法題練習4

技術標籤:寒假演算法練習

題目 String Game

題目內容:
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

解題過程:
題目大意為給定兩個字串算公共子序列的個數,開始以為是數學公式,後來發現想錯了,這是一道dp題。
狀態轉移方程為:
在這裡插入圖片描述
另外,公共子序列,公共子串的題型有很多,也多涉及動態規劃,應該常總結。

全部程式碼:

#include<bits/stdc++.h>
using namespace std;
int dp[5005][5005];
int main(){
	string s1,s2;
    while(cin>>s1>>s2){
        for
(int i=0;i<=s1.length();i++) dp[0][i]=1; for(int j=1;j<=s2.length();j++){ for(int i=1;i<=s1.length();i++){ dp[j][i]=0; } } for(int i=1;i<=s2.length();i++){ for(int j=1;j<=s1.length();j++){ dp[i][j]=dp[i][j-1]; if(s2[i-1]==s1[j-1]){ dp[i][j]+=dp[i-1][j-1]; } dp[i][j] %= 1000000007; } } cout<<dp[s2.length()][s1.length()]<<endl; } }