hdu-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.
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
-----AC------
关于状态转移方程
if(a[i]==b[j])
dp[i][j]=(dp[i-1][j]+dp[i][j-1]+1);
else
dp[i][j]=(dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1]);
dp[i][j]=(dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1]);
例:
序号:1 2 3 4
a[i]:1 2 3 4
b[j]:1 2 3 1
a[i]:1 2 3 4
b[j]:1 2 3 1
假设(从dp[i][j-1]到dp[i][j]):
if(a[i]==b[j]) 前面的j-1个数有dp[i][j-1]种可能,前面j-1个数和p组合又有dp[i][j-1]种可能,加上a[i]==b[j],dp[i][j]=dp[i][j-1]*2+1;
else dp[i][j]=dp[i][j-1];
推导得
a: 1 2 3 4
b: 1 2 3 1
dp[j]: 1 3 7 7
那么就会发现这样会忽略前i-1个数的子序列,所以为了不忽略,下面给出推导正确过程
首先,前面dp[i][j-1],+1是正确的,错在(前面j-1个数和p组合又有dp[i][j-1]种可能,忽略前i-1个数的子序列),实际上可以把a,b倒过来(a[i]==b[j])
例如:
a: 1 2 。。。
b: 1 。 。。。
看成
b: 1 2 。。。j
a: 1 .。。。。i
这样对和p组合可以看成dp[i-1][j]
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 #include<cmath> 5 using namespace std; 6 #define MAXN 1005 7 #define INF 9999999999 8 #define mod 1000000007 9 int dp[MAXN][MAXN]; 10 int main() 11 { 12 int n,m; 13 while(cin>>n>>m) 14 { 15 int a[MAXN],b[MAXN],i,j; 16 memset(dp,0,sizeof(dp)); 17 for(i=1;i<=n;++i) 18 cin>>a[i]; 19 for(i=1;i<=m;++i) 20 cin>>b[i]; 21 for(i=1;i<=n;++i) 22 { 23 for(j=1;j<=m;++j) 24 { 25 if(a[i]==b[j]) 26 dp[i][j]=(dp[i-1][j]+dp[i][j-1]+1)%mod; 27 else 28 dp[i][j]=(dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1])%mod; 29 if(dp[i][j]<0) 30 dp[i][j]+=mod; 31 } 32 } 33 // for(i=1;i<=n;++i) 34 // { 35 // for(j=1;j<=m;++j) 36 // cout<<dp[i][j]<<" "; 37 // cout<<endl; 38 // } 39 cout<<dp[n][m]<<endl; 40 } 41 return 0; 42 }
现在所有的不幸都是以前不努力造成的。。。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!