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.
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
我记得这道题高中的时候这道题是有故事背景的,反正今晚无聊,就当讲个故事吧,背景是这样的:
有一天与A国与B国开战了,B国向A国同时发射了n枚导弹,每枚导弹都有一个高度,A国首脑收到了本国国防部发来的一个好消息和一个坏消息,好消息是A国有一种防空导弹系统可以拦截这种导弹,坏消息是这种防空系统目前有一种缺陷,就是拦截导弹只能越打越高,一发比一发高。问A国最多能拦截多少枚B国导弹。
其实就是求一个最长上升子序列的长度,a表示导弹高度,d表示高度在这枚导弹之下最多能拦截多少颗
若a[i-1]<a[j],则状态转移方程是:d[i]=max(d[1],d[2],d[3]...d[i-1])+1;
#include <iostream> #include <stdio.h> using namespace std; int main() { int i,j,n,a[1002]={0},d[1002]={1},maxd,ans; scanf("%d",&n); for (i=0;i<=n-1;i++) { scanf("%d",&a[i]); } for (i=0;i<=n-1;i++) { maxd=0; for (j=0;j<=i-1;j++) { if (a[i]>a[j]) { if (d[j]>maxd) { maxd=d[j]; } } } d[i]=maxd+1; } ans=0; for (i=0;i<=n-1;i++) { if (d[i]>ans) { ans=d[i]; } } printf("%d",ans); return 0; }