HDU-5791-Two(DP)

来源:互联网 发布:网络保险平台可靠吗 编辑:程序博客网 时间:2024/04/30 01:40

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

题意:给出数组a[n],b[m],求其有多少不连续公共子串(可重复)

题解:dp[i][j]表示A序列前i个数和B序列前j个数的相同子序列对有多少个。

1,a[i]==b[j]时,dp[i][j]=dp[i-1][j]+dp[i][j-1]+1   ,其中1表示a[i]与b[j]单独配对,显然多计算的dp[i-1][j-1]其实是为a[i]和b[j]固定结尾的子串个数;

2,a[i]!=b[j]时,显然结尾不同要减去多余的dp[i-1][j-1].



#include <bits/stdc++.h>using namespace std;const int maxn = 1e3+7;const int mod =  1000000007;int a[maxn];int b[maxn];long long dp[maxn][maxn];int main(){    int n,m;    while(scanf("%d%d",&n,&m)!=EOF)    {        memset(dp,0,sizeof(dp));        for(int i=1; i<=n; ++i)scanf("%d",&a[i]);        for(int i=1; i<=m; ++i)scanf("%d",&b[i]);        for(int i=1; i<=n; ++i)        {            for(int j=1; j<=m; ++j)            {                if(a[i]==b[j])                    dp[i][j]=(dp[i-1][j]+dp[i][j-1]+1)%mod;                else                    dp[i][j]=(dp[i][j-1]+dp[i-1][j]-dp[i-1][j-1]+mod)%mod;            }        }        cout<<dp[n][m]<<endl;    }    return 0;}/*3 21 2 32 13 21 2 31 25 51 3 4 2 51 2 3 4 52 31 21 1 24 31 1 1 21 1 2*/




0 0
原创粉丝点击