从题目就可以看出来,这是一道典型的动规题。
由于是最大上升子序列,所以对任意一个数,在其之后比其大的都不能具有比其更长的子序列,因此每当序列中出现一个更小的数,我们只用考虑以后比其更小的数即可,再加上记忆化搜索即可求解,下面附上代码。
#include <iostream>
#include <cstring>
using namespace std;
int dfs(int x,int y);
const int N = 5e3+5;
int n, p, q = 1;
int a[N];
int c[N];
int b[N];
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
cin >> a[i];
memset(b, -1, sizeof(b));//初始化
p = a[1];//p用来标记此时出现过的最小的值
c[q] = dfs(1, 2);
int ans = c[1];
for (int i = 1; i <= q; i++)//求最大子序列
{
if (c[i] > ans) ans = c[i];
}
ans++;//由于序列未包含其本身,所以需要加1
cout << ans;
return 0;
}
int dfs(int x, int y)//记忆化搜索,x、y均表示数的序号
{
int ans=0;
if (b[x] != -1)//如果已被搜索过,直接赋值
ans = b[x];
else
{
if (y == n)
{
if (a[x] < a[y])
ans = 1;
}
else if (y < n)
{
if (a[x] < a[y])
{
ans = max(dfs(x, y + 1), dfs(y, y + 1) + 1);//求两种情况的最大值
}
else if (a[x] == a[y])
{
ans = dfs(x, y + 1);
}
else if (a[x] > a[y])
{
if (a[y] < p)
{
p = a[y];//更新最小值
++q;
c[q] = dfs(y, y + 1);//求该值的最长上升子序列
}
ans = dfs(x, y + 1);//小于等于自身的数直接跳过
}
}
b[x] = ans;//标记
}
return ans;
}