Longest Ordered Subsequence
Problem Description
A numeric sequence of ai is ordered if a1 < a2 < … < aN. Let the subsequence of the given numeric sequence (a1, a2, …, aN) be any sequence (ai1, ai2, …, aiK), where 1 <= i1 < i2 < … < iK <= N. For example, sequence (1, 7, 3, 5, 9, 4, 8) has ordered subsequences, e. g., (1, 7), (3, 4, 8) and many others. All longest ordered subsequences are of length 4, e. g., (1, 3, 5, 8).
Your program, when given the numeric sequence, must find the length of its longest ordered subsequence.
Input
The first line of input file contains the length of sequence N. The second line contains the elements of sequence - N integers in the range from 0 to 10000 each, separated by spaces. 1 <= N <= 1000
Output
Output file must contain a single integer - the length of the longest ordered subsequence of the given sequence.
Sample Input
7
1 7 3 5 9 4 8
Sample Output
4
题目大意:给一串数列,从中找出最长的有序的子数列
运用动态规划即可
图解:

因为我感觉这题是很简单的dp入门题(可以去看01背包问题),加深理解的话就去画图吧两个for演示一遍(如上)
#include<string>
#include<algorithm>
#include<iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int arr[n],dp[n];//arr【i】放数字,dp【i】放以arr【i】结尾的最长子序列数
for(int i=0;i<n;i++){
cin>>arr[i];
dp[i]=1;//初始化以arr【i】数字结尾的最长子序列长度为1
}
for(int i=1;i<n;i++){//从第二个数开始是因为第一个数dp【1】就是=1
for(int j=0;j<i;j++)//每个以arr【i】结尾的,都要遍历i之前的每一个数
{
//当发现有比arr【j】小的数的时候,比较当前dp【i】与dp【小于arr【i】的数】+1
if(arr[j]<arr[i])
dp[i]=max(dp[i],dp[j]+1);//j是遍历到i前一位的
}
}
//现在以1~n结尾的dp【i】都有了,找出最大的;
int m=1;
for(int i=0;i<n;i++)
{
m=max(m,dp[i]);
}
cout << m << endl;
return 0;
}
/* 我只是一个大一蒟蒻!欢迎大佬指点,若有不同意见可提出,共同学习!*/
885




被折叠的 条评论
为什么被折叠?



