您的位置:首页 > 产品设计 > UI/UE

ZOJ 2432 Greatest Common Increasing Subsequence——dp

2018-03-26 11:00 513 查看
可以在状态转移时压缩一下路径,这样打印时就不需要判重了
注意结果为0时只输出0,这点很坑#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef pair<int, int> P;
const int maxn = 1010;
int T, n1, n2, a[maxn], b[maxn], dp[maxn][maxn];
P path[maxn][maxn];
void output(int i, int j) {
if (dp[i][j] == 0) return;
output(path[i][j].first, path[i][j].second);
printf("%d ", b[j]);
}
int main() {
scanf("%d", &T);
for (int kase = 1; kase <= T; kase++) {
scanf("%d", &n1);
for (int i = 1; i <= n1; i++) scanf("%d", &a[i]);
scanf("%d", &n2);
for (int i = 1; i <= n2; i++) scanf("%d", &b[i]);

memset(dp, 0, sizeof(dp));
memset(path, 0, sizeof(path));
for (int i = 1; i <= n1; i++) {
int maxv = 0, x = 0, y = 0;
for (int j = 1; j <= n2; j++) {
if (a[i] == b[j]) {
dp[i][j] = maxv + 1;
path[i][j].first = x, path[i][j].second = y;
}
else {
dp[i][j] = dp[i-1][j];
path[i][j] = path[i-1][j];
if (a[i] > b[j] && maxv < dp[i-1][j]) {
maxv = dp[i-1][j];
x = i-1, y = j;
}
}
}
}
int ans = 0, pos = 0;
for (int i = 1; i <= n2; i++) {
if (ans < dp[n1][i]) {
ans = dp[n1][i];
pos = i;
}
}
if (kase != 1) printf("\n");
printf("%d\n", ans);
if (ans) {
output(path[n1][pos].first, path[n1][pos].second);
printf("%d\n", b[pos]);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: