题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5791
题意:给你两个序列,求相同的子序列个数,结果对1e9+7取余
题解:dp[i][j]表示两序列分别以i,j为结尾的子问题结果,当i不等于j时,d[i][j] = d[i-1][j]+dp[i][j-1]-dp[i-1][j-1],当i等于j时,d[i][j] = d[i-1][j]+d[i][j-1]+1;
推导过程:当i等于j时,d[i][j] = (i不等于j时的结果) + dp[i-1][j-1] + 1.
1 #include<cstdio> 2 #include<iostream> 3 #include<cstring> 4 using namespace std; 5 6 const int mod = 1e9 + 7; 7 const int maxn = 1005; 8 9 int dp[maxn][maxn]; 10 int a[maxn], b[maxn]; 11 12 int main(){ 13 int n,m; 14 while(scanf("%d%d",&n,&m) == 2){ 15 memset(dp,0,sizeof(dp)); 16 for(int i = 1; i <= n; ++i){ 17 scanf("%d",&a[i]); 18 } 19 for(int i = 1; i <= m; ++i){ 20 scanf("%d",&b[i]); 21 } 22 for(int i = 1; i <= n; ++i){ 23 for(int j = 1; j <= m; ++j){ 24 if(a[i] != b[j]) dp[i][j] = ((dp[i-1][j] + dp[i][j-1]) % mod - dp[i-1][j-1]) % mod; 25 else{ 26 dp[i][j] = ((dp[i-1][j] + dp[i][j-1]) % mod + 1) % mod; 27 } 28 } 29 } 30 printf("%d\n",(dp[n][m] + mod) % mod); 31 } 32 return 0; 33 }