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
此题宜采用动态规划的思想来求解。
解题思路:分别求出以当前输入为子串的最后一个数字时字串的长度,然后找出最大值,这个最大值就是字串的最大长度。(比如对于题目中的输入序列,当前输入为7,求得以7为子串的最后一位的长度为2).
由此,我们有两种解题思想。
(一)
我们用a[S+1]表示要输入的值。a[0]表示当前长度。b[S]表示对应的子串长度。
具体程序如下:
// ceshi.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include<iostream> using namespace std; #define S 1001 //定义长度 int a[S]; //存放原数组 int b[S]; //对应的子串长度 int Max(); //求最大长度 int main() { int N; cin>>N; a[0]=N; //保留N for(int i = 1;i<=N;i++) //从1开始 cin>>a[i]; cout<<Max()<<endl; return 0; } int Max() { int i,j,max,m; b[1] = 1; //赋值 max = 1; //max有最小值 for(i = 2;i<=a[0];i++) { m = 0; //用来记录比a[i]小且子串长度最大的值 for(j = 1;j<i;j++) { if(b[j]>m && a[j]<a[i]) m = b[j]; } b[i] = m+1; if(b[i]>max) max = b[i]; } return max; }
经分析,发现时间复杂度为O(n)。总体来说已经很不错了。仔细分析程序,我们发现时间主要浪费在了反复确定程序中m上了,联想到数据结构中的二分查找,我们对程序进行了如下的改变,使得程序的时间复杂度能够降低到log(n)。
#include<iostream> using namespace std; #define S 1001 int a[S]; int b[S]; int c[S];//c[i]表示a的子串中长度为i的子串末尾的最小值 亮点 int bin(int size,int k);//返回(1,size)中k插入的位置 int Max(); int main() { int N; cin>>N; a[0]=N; for(int i = 1; i<=a[0]; i++) cin>>a[i]; cout<<Max()<<endl; return 0; } int bin(int size,int k) { int l = 1,r = size; while(l<=r) { int mid = (l+r)/2; if(k>c[mid] && k<=c[mid+1]) return mid+1; else if(k<c[mid]) r = mid-1; else l = mid+1; } } int Max() { int i,j,max=1; c[1] = a[1]; b[1] = 1; for(i = 2; i<=a[0]; i++) { if(a[i]<=c[1]) j = 1; else if(a[i]>c[max]) j = ++max; else j = bin(max,a[i]); c[j] = a[i]; b[i] = j; } return max; }