VK Cup 2012 Round 2 Substring and Subsequence(線性dp/子序列dp)

題目

給定一個小寫字母串s(|s|<5e3)和一個小寫字母串t(|t|<5e3)

求x是s的子串,y是t的子序列,且x和y相同的合法方案數,答案對1e9+7取模

只要位置不完全相同,即使表示的是相同的內容,都算作不同的x,不同的y

Two substrings s[a... b] and s[c... d] are considered to be different if a ≠ c or b ≠ d.

For example, if s="codeforces", s[2...2] and s[6...6] are different, though their content is the same.

Two subsequences u = s[p1p2... p|u|] and v = s[q1q2... q|v|] are considered different if the sequences p and q are different.

題解

dp[i][j]表示s串中第i個字母必取,t串中第j個字母必取的合法方案數

子序列dp,即考慮在已經的合法方案後面補了一個字母,從先前的方案裏添後繼

如果x最後一個字母是s[i],y最後一個字母是t[j],

則x上一個字母一定是s[i-1],y上一個字母可以從t[1]-t[j-1]裏取,

dp[i][j]=dp[i-1][1]+...+dp[i-1][j-1]+1,加的1,是認爲先前的x和先前的y都是空串

暴力算O(n^3),用前綴和搞到O(n^2)

代碼

#include<bits/stdc++.h>
using namespace std;
const int N=5e3+5,mod=1e9+7;
typedef long long ll;
char s[N],t[N];
int dp[N][N],ans;
int main()
{
	scanf("%s%s",s+1,t+1);
	for(int i=1;s[i];++i)
	{
		for(int j=1;t[j];++j)
		{
			if(s[i]==t[j])
			{
				dp[i][j]=dp[i-1][j-1]+1;
				ans=(ans+dp[i][j])%mod;
			}
			dp[i][j]=(dp[i][j]+dp[i][j-1])%mod;
		}
	}
	printf("%d\n",ans);
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章