最长上升子序列二分做法的路径保存
作者:
22hhlin
,
2024-05-19 16:30:44
,
所有人可见
,
阅读 6
#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
int a[N], q[N];
int n;
int path[N], t[N];
int main()
{
scanf("%d", &n);
for (int i = 0; i < n; i++) scanf("%d", &a[i]);
q[0] = -0x3f3f3f3f;
int len = 0;
for (int i = 0; i < n; i++)
{
int l = 0, r = len;
while (l < r)
{
int mid = l + r + 1 >> 1;
if (q[mid] < a[i]) l = mid;
else r = mid - 1;
}
len = max(len, l + 1);
q[l + 1] = a[i];
path[i] = l + 1; //记录下a[i]在dp中的最长长度代表多少
}
cout << len << endl;
for (int i = n - 1, s = len; i >= 0; i--) //从后往前遍历依次找最大的就行
{
if (!s) break;
else
{
if (path[i] == s)
{
t[s] = a[i];
s--;
}
}
}
for (int i = 1; i <= len; i++)
cout << t[i] << " ";
return 0;
}
最长上升子序列II