Subsequence
題目背景:
分析:DP + 複雜度分析
這個題感覺難點在複雜度分析,看似總狀態數n * m轉移複雜度k,但是實際上,可以證明得到答案數與k的乘積是小於(n + m)的,證明:假設當前匹配到A的第j位,B的第i位,那麼第j + 1位到第j + k - 1位,那麼一定有一個數沒有出現過,那麼選擇這個數就會讓i + j增加k,所以每一次操作至少能增加k,所以最後的答案不超過(n + m) / k,所以直接按照O(n3)的方式DP就可以了,實際複雜度爲O(n2),定義dp[i][j]表示,當前枚舉第i位,在A串中匹配到j,dp[i][j]表示在B串中匹配到的最後的位置。預處理next_a[i][j]表示第i位之後第一個j出現的位置,最後結尾設爲n + 1,那麼當dp[i][n + 1] = m + 1時,說明i就是可行的長度了。
Source:
/*
created by scarlyw
*/
#include <cstdio>
#include <string>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <cmath>
#include <cctype>
#include <vector>
#include <set>
#include <queue>
#include <ctime>
#include <bitset>
inline char read() {
static const int IN_LEN = 1024 * 1024;
static char buf[IN_LEN], *s, *t;
if (s == t) {
t = (s = buf) + fread(buf, 1, IN_LEN, stdin);
if (s == t) return -1;
}
return *s++;
}
///*
template<class T>
inline void R(T &x) {
static char c;
static bool iosig;
for (c = read(), iosig = false; !isdigit(c); c = read()) {
if (c == -1) return ;
if (c == '-') iosig = true;
}
for (x = 0; isdigit(c); c = read())
x = ((x << 2) + x << 1) + (c ^ '0');
if (iosig) x = -x;
}
//*/
const int OUT_LEN = 1024 * 1024;
char obuf[OUT_LEN], *oh = obuf;
inline void write_char(char c) {
if (oh == obuf + OUT_LEN) fwrite(obuf, 1, OUT_LEN, stdout), oh = obuf;
*oh++ = c;
}
template<class T>
inline void W(T x) {
static int buf[30], cnt;
if (x == 0) write_char('0');
else {
if (x < 0) write_char('-'), x = -x;
for (cnt = 0; x; x /= 10) buf[++cnt] = x % 10 + 48;
while (cnt) write_char(buf[cnt--]);
}
}
inline void flush() {
fwrite(obuf, 1, oh - obuf, stdout);
}
/*
template<class T>
inline void R(T &x) {
static char c;
static bool iosig;
for (c = getchar(), iosig = false; !isdigit(c); c = getchar())
if (c == '-') iosig = true;
for (x = 0; isdigit(c); c = getchar())
x = ((x << 2) + x << 1) + (c ^ '0');
if (iosig) x = -x;
}
//*/
const int MAXN = 4000 + 10;
int n, m, k;
int dp[MAXN][MAXN], a[MAXN], b[MAXN];
int next_a[MAXN][MAXN], next_b[MAXN][MAXN];
inline void read_in() {
R(n), R(m), R(k);
for (int i = 1; i <= n; ++i) R(a[i]);
for (int i = 1; i <= m; ++i) R(b[i]);
for (int i = 1; i <= k; ++i) {
next_a[n][i] = next_a[n + 1][i] = n + 1;
next_b[m][i] = next_b[m + 1][i] = m + 1;
}
for (int i = n - 1; i >= 0; --i) {
for (int j = 1; j <= k; ++j)
next_a[i][j] = next_a[i + 1][j];
next_a[i][a[i + 1]] = i + 1;
}
for (int i = m - 1; i >= 0; --i) {
for (int j = 1; j <= k; ++j)
next_b[i][j] = next_b[i + 1][j];
next_b[i][b[i + 1]] = i + 1;
}
}
inline void solve() {
memset(dp, -1, sizeof(dp));
dp[0][0] = 0;
for (int i = 0; ; ++i) {
for (int j = 0; j <= n + 1; ++j) {
if (dp[i][j] == -1) continue ;
if (j == n + 1 && dp[i][j] == m + 1) std::cout << i, exit(0);
for (int c = 1; c <= k; ++c)
dp[i + 1][next_a[j][c]] = std::max(dp[i + 1][next_a[j][c]],
next_b[dp[i][j]][c]);
}
}
}
int main() {
freopen("subsequence.in", "r", stdin);
freopen("subsequence.out", "w", stdout);
read_in();
solve();
return 0;
}