您的位置:首页 > 大数据 > 人工智能

DP——Two ( HDU 5791 ) ( 2016 Multi-University Training Contest 5 1011 )

2016-08-02 21:28 399 查看
题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=5791

分析:

给出两串数字,求求它们有多少相同的子序列。

题解:

确定DP方程:

DP[i][j]表示A串前i个字符和B串前j个字符之间由多少相同的子序列,

dp[i][j] = (dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1])%MOD;//加上前面的串的相同的子序列数量
if(dp[i][j] < 0)    //<注释>
dp[i][j] += MOD;//加个MOD变正
if(a[i] == b[j])
dp[i][j] = (dp[i][j]+dp[i-1][j-1]+1)%MOD;    //如果当前字符相等,那么前面的dp[i-1][j-1]就能和这个新的相等字符匹配一遍,所以需要加上dp[i-1][j-1]+1


AC代码:

#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <cctype>
#include <stack>
#include <map>
#include <set>
#include <queue>
using namespace std;
typedef pair<int,int> Pii;
typedef long long LL;
typedef unsigned long long ULL;
typedef long double LD;
int a[1234];
int b[1234];
int N,M;
const int MOD = 1000000007;

int dp[1234][1234];

int solve()
{
memset(dp, 0, sizeof(dp));
for(int i=1;i<=N;i++)
{
for(int j=1;j<=M;j++)
{
dp[i][j] = (dp[i-1][j]+dp[i][j-1]-dp[i-1][j-1])%MOD;
if(dp[i][j] < 0)
dp[i][j] += MOD;
if(a[i] == b[j])
dp[i][j] = (dp[i][j]+dp[i-1][j-1]+1)%MOD;
}
}
return dp
[M];
}

int main()
{
while(~scanf("%d%d", &N, &M) )
{
for(int i=1;i<=N;i++)
scanf("%d", &a[i]);
for(int j=1;j<=M;j++)
scanf("%d", &b[j]);

LL ans = solve();
cout << ans << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  2016多校 DP