最长上升子序列
朴素版
O(n²)
int res = 0;
for (int i = 0; i < n; i++)
{
f[i] = 1;
for (int j = 0; j < i; j++)
{
if (a[j] < a[i])
{
f[i] = max(f[i], f[j] + 1);
}
}
res = max(res, f[i]);
}
cout << res << endl;
优化版
O(nlogn)
vector<int> stk;
stk.push_back(a[0]);
for (int i = 1; i < n; i++)
{
if (a[i] > stk.back())
{
stk.push_back(a[i]);
}
else
{
*lower_bound(stk.begin(), stk.end(), a[i]) = a[i];
}
}
cout << stk.size() << endl;
最长公共子序列
O(nm)
char a[N], b[M];
int f[N][M];
cin >> n >> m >> a + 1 >> b + 1;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
f[i][j] = max(f[i - 1][j], f[i][j - 1]);
if (a[i] == b[j])
{
f[i][j] = max(f[i][j], f[i - 1][j - 1] + 1);
}
}
}
cout << f[n][m] << endl;
最长公共上升子序列
O(n²)
int a[N], b[N], f[N][N];
for (int i = 1; i <= n; i++)
{
int maxv = 1;
for (int j = 1; j <= n; j++)
{
f[i][j] = f[i - 1][j];
if (a[i] == b[j])
{
f[i][j] = max(f[i][j], maxv);
}
if (a[i] > b[j])
{
maxv = max(maxv, f[i - 1][j] + 1);
}
}
}
int res = 0;
for (int i = 1; i <= n; i++)
{
res = max(res, f[n][i]);
}
cout << res << endl;