算法1 O(n2)动态规划
f [i] :长度为i + 1的序列中最大上升子序列的长度
状态转移:f[i] = max(f[j] + 1, f[i]) i = 0~n-1, j = 0~i
#include <iostream>
using namespace std;
const int N = 1010;
int n;
int a[N], f[N];
int main()
{
cin >> n;
for(int i = 0; i < n; i ++ ) scanf("%d", &a[i]);
for(int i = 0; i < n; i ++ )
{
f[i] = 1;
for(int j = 0; j < i; j ++ )
{
if(a[j] < a[i])
{
if(f[j] + 1 > f[i]) f[i] = f[j] + 1;
}
}
}
int res = 0;
for(int i = 0; i < n; i ++ )
{
res = max(res, f[i]);
}
cout << res << endl;
return 0;
}
算法2 O(nlogn)动态规划 + 二分
f[i]:以下标为i的元素为结尾的最长子序列的长度
状态转移:
a[i]>f[cnt - 1]:f[cnt ++] = a[i]
a[i]<=f[cnt - 1]:找到子序列中大于等于a[i]的最小的数f[r],f[r] = a[i] (保证后续更新的准确)
#include <iostream>
using namespace std;
const int N = 1010;
int n, cnt;
int a[N], f[N];
int main()
{
cin >> n;
for(int i = 0; i < n; i ++ ) scanf("%d", &a[i]);
f[cnt ++ ] = a[0];
for(int i = 1; i < n; i ++ )
{
if(a[i] > f[cnt - 1]) f[cnt ++ ] = a[i];
else
{
int l = 0, r = cnt - 1;
while(l < r)
{
int mid = l + r >> 1;
if(f[mid] >= a[i]) r = mid;
else l = mid + 1;
}
f[r] = a[i];
}
}
cout << cnt << endl;
return 0;
}
原文:https://www.cnblogs.com/xulizs666/p/14649618.html