dp[i][j]表示A序列前i个数和B序列前j个数的相同子序列对有多少个。复杂度O(n^2)O(n?2??)
/*by*/ #include <iostream> #include <algorithm> #include <cstdio> #include <cstring> using namespace std; typedef long long LL; const LL N=1010; const LL mod=1000000007; LL a[N],b[N]; LL dp[N][N]; int main() { LL n,m,i,j; while(~scanf("%lld%lld",&n,&m)) { memset(dp,0,sizeof(dp)); for(i=1; i<=n; i++) scanf("%lld",&a[i]); for(i=1; i<=m; i++) scanf("%lld",&b[i]); for(i=1; i<=n; i++) { for(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-1][j]+dp[i][j-1]-dp[i-1][j-1]+mod)%mod;/*去重,相减可能是负数,先加个mod*/ } } printf("%lld\n",dp[n][m]); } return 0; }
时间: 2024-10-12 23:11:14