HDU 5791
HDU 5791
题意:
给出两个串和它们的长度,求有多少对相同子序列。
例如, {1,1,2} 有 7 个子序列 {1},{1},{2},{1,1},{1,2},{1,2},{1,1,2}.
最后结果对 1e9 + 7 取余.
解题 :
= = DP
如果 a[i] == b[j] , d[i][j] = d[i-1][j] + d[i][j-1] + 1;
否则 d[i][j] = d[i-1][j] + d[i][j-1] - d[i-1][j-1];
取余的时候小心负数的情况 = =
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> #include <string> #include <map> #include <cmath> using namespace std; const int maxn = 1010; const int MOD = 1e9+7; int a[maxn],b[maxn]; int d[maxn][maxn]; int main() { int n,m,cnt; while(scanf("%d%d",&n,&m)!=EOF) { for(int i=1;i<=n;i++) scanf("%d",&a[i]); for(int i=1;i<=m;i++) scanf("%d",&b[i]); d[0][0] = d[1][0] = d[0][1] = 0; for(int i=1;i<=n;i++) { for(int j=1;j<=m;j++) { d[i][j] = d[i-1][j] + d[i][j-1] - d[i-1][j-1]; if(a[i] == b[j]) d[i][j] = d[i-1][j] + d[i][j-1] + 1; d[i][j] = ( (d[i][j] % MOD) + MOD) % MOD; } } printf("%d\n",d[n][m]); } return 0; }