简单的dp(dp专题)

题目链接:https://vjudge.net/contest/216347#problem/C

 
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.
InputThe input contains multiple test cases.

For each test case, the first line cantains two integers N,M(1N,M1000)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.OutputFor 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
 题目大意:给你两个数组,要你求出这两个数组有多少个公共子串
个人思路:说是简单dp,但是要是想不出来就很不简单了,不说废话了,这题要求出状态转移方程,方法是用面积来求
如图,当a[i]!=b[j]时,dp[i][j]=dp[i][j-1]+dp[i-1][j]-dp[i-1][j-1],因为多加了一个dp[i-1][j-1]的面积
当a[i]==b[j]时,a[i]等于b[j]本身构成一个相等子串,dp[i-1][j-1]加上a[i],b[i]也构成新的子串,所以在不想等的情况下加上这两个条件
dp[i][j]=dp[i-1][j]+dp[i][j-1]+1
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<cmath>
#include<math.h>
#include<algorithm>
#include<set>
typedef long long ll;
using namespace std;
const ll INF=1e9+7;
//#define INF 1e9+7
ll dp[1100][1100];
int main()
{
    ll n,m;
    ll a[1100],b[1100];

    while(scanf("%I64d%I64d",&n,&m)!=EOF)
    {
        memset(dp,0,sizeof(dp));
        for(int i=1;i<=n;i++)
        {
            scanf("%I64d",&a[i]);
        }
        for(int i=1;i<=m;i++)
            scanf("%I64d",&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][j-1]+dp[i-1][j]-dp[i-1][j-1]+INF)%INF;//注意括号里面可能是负数,不加上会wa
                }
                else
                {
                    dp[i][j]=(dp[i][j-1]+dp[i-1][j]+1)%INF;
                }
            }
        }
        printf("%I64d\n",dp[n][m]);
    }
    return 0;
}

  

 

猜你喜欢

转载自www.cnblogs.com/caijiaming/p/9294403.html