洛谷P3637题解

从题目就可以看出来,这是一道典型的动规题。

由于是最大上升子序列,所以对任意一个数,在其之后比其大的都不能具有比其更长的子序列,因此每当序列中出现一个更小的数,我们只用考虑以后比其更小的数即可,再加上记忆化搜索即可求解,下面附上代码。

#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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值