题意:两个数列a,b,求相同的子序列有多少对,内容相同位置不同也算不同。
题解:dp[i][j]表示a数列前i个数个 b数列前j个数 有多少对
递推方程: dp[i][j] = dp[i-1][j-1]( a[i]和b[j]都不用 ) + ∑(k<i&&a[k]==b[j])dp[k-1][j-1] + ∑(k<=j&&a[i]==b[k])dp[i-1][k-1];
for (int i = ; i <= n; ++i) {
for (int j = ; j <= m; ++j) {
dp[i][j] = ;
for (int k = ; k < i; ++k)
if (a[k] == b[j]) dp[i][j] = (dp[i][j] + dp[k-][j-]) % MOD;
for (int k = ; k <= j; ++k)
if (a[i] == b[k]) dp[i][j] = (dp[i][j] + dp[i-][k-]) % MOD;
dp[i][j] = (dp[i][j] + dp[i-][j-]) % MOD; }
}
O(n^3)会超时,所以在每一步多求一些辅助值,可以优化到O(n^2)。
我知道这种做法没问题,但是比赛的时候打死都调不出来,最后还是队友做的,心烦。
突然想到我的做法貌似很蠢……哎 不管了。。。反正过了。。。
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <queue>
#include <vector>
#include <cmath>
#define CLR(x, r) memset(x, r, sizeof (x))
#define PF(x) printf("debug:%d\n", x) using namespace std;
typedef long long ll; const int N = ;
const ll MOD = ;
int a[N], b[N];
ll dp[N][N];
ll ax[N];
ll bx[N]; int main(int argc, char const *argv[])
{
freopen("in", "r", stdin);
int n, m;
while (~scanf("%d%d", &n, &m)) {
for (int i = ; i <= n; ++i) scanf("%d", a+i);
for (int i = ; i <= m; ++i) scanf("%d", b+i); for (int i = ; i <= n; ++i) dp[i][] = ;
for (int i = ; i <= m; ++i) dp[][i] = ;
CLR(ax, );
for (int j = ; j <= m; ++j) {
if (b[j] == a[]) bx[j] = bx[j-] + dp[][j-];
else bx[j] = bx[j-];
}
for (int i = ; i <= n; ++i) {
int ant = a[i+];
for (int j = ; j <= m; ++j) {
dp[i][j] = ; dp[i][j] = (dp[i][j] + ax[j]) % MOD; // 用到 b[j]
dp[i][j] = (dp[i][j] + bx[j]) % MOD; // 用到 a[i]
dp[i][j] = (dp[i][j] + dp[i-][j-]) % MOD; if (b[j] == ant) {
bx[j] = (bx[j-] + dp[i][j-]) % MOD;
} else {
bx[j] = bx[j-];
} if (b[j] == a[i]) {
ax[j] = (ax[j] + dp[i-][j-]) % MOD;
} }
} cout << (dp[n][m] - + MOD) % MOD << endl;
}
return ;
}