最长上升子序列

来源:互联网 发布:淘宝代理货源平台 编辑:程序博客网 时间:2024/06/05 01:44
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,

递推公式:dp[i] = max(1,dp[j]+1) (j<i且a[j]<a[i],1为本身的个数)

#include <stdio.h>#include <string.h>#include <iostream>#include <algorithm>#include <vector>#include <queue>#include <set>#include <map>#include <string>#include <math.h>#include <stdlib.h>using namespace std;const int MAXN=1010;int n;int a[MAXN];int dp[MAXN];void solve(){   int result=0;   for(int i=0;i<n;i++){    dp[i]=1;    for(int j=0;j<i;j++){        if(a[i]>a[j])            dp[i]=max(dp[i],dp[j]+1);    }    result=max(result,dp[i]);   }   printf("%d\n",result);    return ;}int main(){    scanf("%d",&n);    for(int i=0;i<n;i++)      scanf("%d",&a[i]);    solve();    return 0;}

本份代码接近O(n*n),感觉耗时间太多,下面用二分优化

#include <cstdio>#include <cmath>#include <cstring>#include <iostream>#include <vector>#include <queue>using namespace std;const int MA=100009;int dp[MA],n;int bin(int len,int k){    int l = 1, r = len;    while(l <= r)    {        int mid = (l+r)/2;        if(k > dp[mid])            l = mid+1;        else            r = mid-1;    }    return l;}int LIS(int a[]){    int i,j,ans=1;    dp[1] = a[1];    for(i = 2; i <= n; i++)    {        if(a[i] < dp[1])//如果比最小的还小            j = 1;        else if(a[i] >= dp[ans])//如果比最大的还大            j = ++ans;        else            j = bin(ans,a[i]);        dp[j] = a[i];    }    return ans;}int main(){    int t,k;    int a[MA],b[MA];    scanf("%d",&t);    while(t--)    {        scanf("%d %d",&n,&k);        for(int i=1;i<=n;i++)        {            scanf("%d",&a[i]);            b[i]=-a[i]+100005;        }        int m1,m2;        memset(dp,0,sizeof(dp));        m1=LIS(a);        memset(dp,0,sizeof(dp));        m2=LIS(b);        if(m1>=n-k||m2>=n-k) printf("A is a magic array.\n");        else printf("A is not a magic array.\n");    }    return 0;}


原创粉丝点击