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;
}