题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5791
#include<bits/stdc++.h>
using namespace std;
#define debug puts("YES");
#define rep(x,y,z) for(int (x)=(y);(x)<(z);(x)++)
#define ll long long
#define lrt int l,int r,int rt
#define lson l,mid,rt<<1
#define rson mid+1,r,rt<<1|1
#define root l,r,rt
#define mst(a,b) memset((a),(b),sizeof(a))
#define pii pair<ll,ll>
#define mk(x,y) make_pair(x,y)
const int maxn =1e3+5;
const int mod=1e9+7;
const int ub=1e6;
ll powmod(ll x,ll y){ll t; for(t=1;y;y>>=1,x=x*x%mod) if(y&1) t=t*x%mod; return t;}
ll gcd(ll x,ll y){return y?gcd(y,x%y):x;}
/*
题目大意:给定两个整数序列求其子序列相同的pair数。
题目分析:这题被分类到DP里面我才照着DP思路想的,
首先这题初始化很简单,
然后考虑对于给定的行,按列更新,假设i位置和j位置的已经更新好了,
那么新增一个j+1的数,首先根据组合要加上dp[i][j],如果i位置数和j+1位置数一样,
那么再加上dp[i-1][j]+1(记得加一).
剩下的,是之前维护好的,在特定的列中,其以a[i]数结尾的dp值之和,
详情看代码,,一个维护的技巧而已。
时间复杂度:O(n*n).
*/
int n,m;
int a[maxn],b[maxn];///序列
ll dp[maxn][maxn],cnt[maxn][maxn];
int main(){
while(scanf("%d%d",&n,&m)!=EOF){
mst(dp,0),mst(cnt,0);
rep(i,0, n) scanf("%d",&a[i]);
rep(i,0,m) scanf("%d",&b[i]);
dp[0][0]=1LL*(a[0]==b[0]);
rep(i,1,m){
dp[0][i]=dp[0][i-1]+1LL*(a[0]==b[i]);
cnt[i][a[0]]++;
}
rep(i,1,n ){
dp[i][0]=dp[i-1][0]+1LL*(a[i]==b[0]);
cnt[0][a[i]]++;
}
rep(i,1,n) rep(j,1,m){
if(a[i]==b[j]) dp[i][j]=(dp[i][j]+dp[i-1][j-1]+1)%mod;
dp[i][j]=(dp[i][j]+cnt[j][b[j]])%mod;
dp[i][j]=(dp[i][j]+dp[i][j-1])%mod;
cnt[j][a[i]]=(cnt[j][a[i]]+1+dp[i-1][j-1]%mod)%mod;
}
///for(int i=0;i<n;i++,puts("")) for(int j=0;j<m;j++) printf("%d%c",dp[i][j],j==m-1?'\n':' ');
printf("%lld\n",dp[n-1][m-1]);
}
return 0;
}