http://acm.hdu.edu.cn/showproblem.php?pid=5791
Two
Problem Description
Alice gets two sequences A and B. A easy problem comes. How many pair of sequence A‘ and sequence B‘ are same. For example, {1,2} and {1,2} are same. {1,2,4} and {1,4,2} are not same. A‘ is a subsequence of A. B‘ is a subsequence of B. The subsequnce can be not continuous. For example, {1,1,2} has 7 subsequences {1},{1},{2},{1,1},{1,2},{1,2},{1,1,2}. The answer can be very large. Output the answer mod 1000000007.
Input
The input contains multiple test cases.
For each test case, the first line cantains two integers N,M(1≤N,M≤1000). The next line contains N integers. The next line followed M integers. All integers are between 1 and 1000.
Output
For each test case, output the answer mod 1000000007.
Sample Input
3 2
1 2 3
2 1
3 2
1 2 3
1 2
Sample Output
2
3
题意:有两个串,求两两子串相同的个数有多少(可以不连续)。
思路:有点类似于LCS的DP。
1 #include <cstdio> 2 #include <algorithm> 3 #include <cstring> 4 using namespace std; 5 #define N 1005 6 #define MOD 1000000007 7 typedef long long LL; 8 9 LL dp[N][N]; 10 int a[N], b[N]; 11 /* 12 1 2 3 13 2 1 14 */ 15 int main() 16 { 17 int n, m; 18 while(~scanf("%d%d", &n, &m)) { 19 dp[0][0] = 0; 20 for(int i = 1; i <= n; i++) { 21 scanf("%d", a+i); 22 dp[i][0] = 0; 23 } 24 for(int i = 1; i <= m; i++) { 25 scanf("%d", b+i); 26 dp[0][i] = 0; 27 } 28 /* 29 有这三部分 30 dp[i-1][j-1] 31 dp[i-1][j] - dp[i-1][j-1] 32 dp[i][j-1] - dp[i-1][j-1] 33 如果不匹配的话 dp[i][j] = dp[i-1][j] - dp[i-1][j-1] + dp[i][j-1] - dp[i-1][j-1] + dp[i-1][j-1] 34 匹配的话 dp[i][j] = 不匹配的状态 + dp[i-1][j-1] + 1 35 dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1] 表示当前不匹配的状态有多少种,因为dp[i-1][j]和dp[i][j]中有dp[i-1][j-1]重复,所以要减去一个 36 如果当前匹配的话,就不用减去,因为要留一个来和当前的a[i]和b[j]匹配。 37 */ 38 for(int i = 1; i <= n; i++) { 39 for(int j = 1; j <= m; j++) { 40 if(a[i] == b[j]) { 41 dp[i][j] = (dp[i-1][j] + dp[i][j-1] + 1 + MOD) % MOD; 42 } else { 43 dp[i][j] = (dp[i-1][j] + dp[i][j-1] - dp[i-1][j-1] + MOD) % MOD; 44 } 45 } 46 } 47 48 printf("%I64d\n", dp[n][m] % MOD); 49 } 50 return 0; 51 }