22-Two(公共子序列的个数)
http://acm.hdu.edu.cn/showproblem.php?pid=5791
Two
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 2599 Accepted Submission(s): 1111
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.
1 2 3
2 1
3 2
1 2 3
1 2
3
题目分析:
HDU多校第五场的1011。
题目大意是有两个序列,其长度为n和m。求他们的子序列相同的个数。
DP题,推导公式,dp[i][j]表示在第一个序列前i个位置和第二个序列前j个位置下,有多少种子序列相同情况。
可以推出,如果某个第一个序列的i位置与第二个序列j位置元素不同,其dp[i][j]=dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1]。
将i和j分开看,如果没有i,第一个序列前i-1个与第二个序列前j个有多少种相同的,和第一个序列前i个与第二个序列前j-1个有多少相同。同时,需要减掉dp[i-1][j-1],因为在之前将第一个序列前i-1和第二个序列前j-1计算了两边。
如果第一个序列i位置与第二个序列j位置元素相同,需要加上i与j相同的一个之外,还需要加上dp[i-1][j-1],因为dp[i-1][j-1]可以与i配对相同,也可以与j配对相同,于是就需要重复计算一次。
dp[i][j]=dp[i-1][j]+dp[i][j-1]+1。(实际上对于最后相等的话,算上最后一对就有a[i - 1][j - 1] + 1种(肯定比a[i-1][j - 1多一种),不算的话,则是a[i-1][j] + a[i][j - 1] - a[i - 1][j - 1])
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
int a[1005];
int b[1005];
long long dp[1005][1005];
int mod = 1000000007; long long find(int i, int j){
if(i < 0 || j < 0)
return 0;
if(dp[i][j] != -1){ //如果是 != 0 会TLE!!! 因为这个题就算搜索过也有大量为0的情况,故初始化的初始值要避免用0
return dp[i][j];
}
if(a[i] == b[j]){
return dp[i][j] = (find(i - 1, j) + find(i, j - 1) + 1) % mod; //这里实际上是还有 + find(i-1,j-1) - find(i-1,j-1);
}
else{
return dp[i][j] = (find(i - 1, j) + find(i, j - 1) - find(i - 1, j - 1) + mod) % mod; //加一个mod防止有负的
}
} int main(){
// std::ios::sync_with_stdio(false);
int n, m;
while(cin >> n >> m){
memset(dp, -1, sizeof(dp));
for(int i = 0; i < n; i++){
cin >> a[i];
// scanf("%d", &a[i]);
}
for(int j = 0; j < m; j++)
cin >> b[j];
// scanf("%d", &b[j]);
cout << find(n - 1, m - 1) << endl;
}
return 0;
}
最新文章
- html学习第二天—— 第七章——CSS样式基本知识
- ubuntu配置NFS
- h5
- 【FOL】第二周
- Java--剑指offer(5)
- jquery and jquery validation 常见问题解决
- 《Java程序设计》第6周学习总结
- 【英语】Bingo口语笔记(74) - put系列
- 【Ionic】---AngularJS扩展基本布局
- OA学习笔记-008-岗位管理Action层实现
- js正则表达式验证字符长度
- 轻型ORM--Dapper
- 第八章 监控 Zabbix
- void main(), int main() 和int main(void)的区别
- Vim自动补全神器YouCompleteMe的配置
- poj 1228 稳定凸包
- COGS 2396 2397 [HZOI 2015]有标号的强连通图计数
- 解决Mac下idea运行速度慢
- python3 CERTIFICATE_VERIFY_FAILED错误 certificate verify failed
- Prism 4 文档 ---第11章 部署Prism应用程序