题意:求两个序列的最长公共严格上升子序列的长度。
NOI 题库里有这道题,序列长度<=500。容易想到一个 O(n3) 的做法:设f[i][j]
为a[0..i]、b[0..j]以i、j结尾的最长公共严格上升子序列的长度,同时维护g[i][j] = max { f[k][j] [k<=i & a[k]=b[j]] } + 1
。实现中,我把g
滚动了,于是需要逆序枚举。由于NOI题库没有Special Judge,交到了CodeVS。作为 O(n3) 的算法当然可以被卡,不过神奇地通过了所有测试数据。
网上有更好的做法。首先,f
数组完全可以不要。g[i][j] = max { g[i-1][k] [k<j & b[k]<b[j]] } + 1 (a[i]=b[j]), g[i-1][j] (a[i]!=b[j])
。外层枚举i
,内层枚举j
,发现条件中的b[k]<b[j]
变为b[k]<一个常量
,从左到右维护满足该条件的max { g[i-1][k] }
即可。
记录字典序最小的方案可以用vector
:http://stone906229046.blog.163.com/blog/static/267075001201610781331357/
O(n3)
#include <cstdio>
#include <algorithm>
using namespace std;
const int MAX_M = 3005;
int a[MAX_M], b[MAX_M], f[MAX_M][MAX_M], g[MAX_M];int main()
{int m, n;scanf("%d", &m);for (int i = 0; i < m; ++i)scanf("%d", &a[i]);
// scanf("%d", &n);n = m;for (int i = 0; i < n; ++i)scanf("%d", &b[i]);int ans = 0;for (int j = 0; j < n; ++j)if (a[0] == b[j])f[0][j] = g[j] = 1;for (int i = 1; i < m; ++i) {for (int j = n-1; j >= 0; --j) {if (a[i] != b[j])continue;f[i][j] = 1;for (int k = 0; k < j; ++k)if (b[k] < b[j])f[i][j] = max(f[i][j], g[k]+1);g[j] = max(g[j], f[i][j]);ans = max(ans, f[i][j]);}}printf("%d\n", ans);return 0;
}
O(n2)
#include <cstdio>
#include <algorithm>
using namespace std;
const int MAX_M = 3005;
int a[MAX_M], b[MAX_M], g[MAX_M];int main()
{int m, n;scanf("%d", &m);for (int i = 0; i < m; ++i)scanf("%d", &a[i]);n = m;for (int i = 0; i < n; ++i)scanf("%d", &b[i]);int ans = 0;for (int i = 0; i < m; ++i) {int v = 0; // v = g[k], k<j & b[k]<b[j]=a[i]for (int j = 0; j < n; ++j) {if (b[j] < a[i])v = max(v, g[j]);else if (b[j] == a[i]) {g[j] = max(g[j], v+1);ans = max(ans, g[j]);}}}printf("%d\n", ans);return 0;
}