zoj 2136 Longest Ordered Subsequence

本文介绍了一种使用动态规划算法解决数字序列中寻找最长不下降子序列的方法。通过定义状态转移方程,逐步计算每个元素结尾的最长不下降序列长度,并最终确定整个序列的最大长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
动态规划问题
找出一个数字序列中最长的不下降序列
用dp[i]存储序列中以i结尾的最长的不下降序列的长度
则对于s[i]
以s[i]结尾的最长不下降序列的长度就是MAX{dp[s[j]]}+1  (s[j]<=s[i]&&j==0...i-1)
以sublen记录最大的dp[i]即为最长的不下降序列的长度
第一道dp题。。。
*/
#define LOCAL
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<cstdlib>
#include<iomanip>
#include<string>
#include<algorithm>
#include<ctime>
#include<stack>
#include<queue>
#include<vector>
#define N 1005
using namespace std;
int main()
{
#ifdef LOCAL
       freopen("input.txt","r",stdin);
       freopen("output.txt","w",stdout);
#endif
	int ncase,slen,sublen,first=1,i,j,dp[N*10],s[N],found;
	cin>>ncase;
	while(ncase--)
	{
		cin.get();
		cin>>slen;
		for(i=0;i<slen;i++)
			cin>>s[i];
		memset(dp,0,sizeof(dp));
		dp[s[0]]=1;sublen=1;
		for(i=1;i<slen;i++)
		{
			found=0;
			for(j=0;j<i;j++)
			{
				if(s[j]<s[i]&&dp[s[j]]+1>dp[s[i]])
				{dp[s[i]]=dp[s[j]]+1;if(dp[s[i]]>sublen) sublen=dp[s[i]];found=1;}
			}
			if(!found){dp[s[i]]=1;}
		}
		if(first){first=0;}
		else{cout<<endl;}
		cout<<sublen<<endl;
	}
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值