51 nod 1134 最长递增子序列 (O(nlogn))

1134 最长递增子序列 

基准时间限制:1 秒 空间限制:131072 KB 分值: 0 难度:基础题

给出长度为N的数组,找出这个数组的最长递增子序列。(递增子序列是指,子序列的元素是递增的)

例如:5 1 6 8 2 4 5 10,最长递增子序列是1 2 4 5 10。

Input

第1行:1个数N,N为序列的长度(2 <= N <= 50000)
第2 - N + 1行:每行1个数,对应序列的元素(-10^9 <= S[i] <= 10^9)

Output

输出最长递增子序列的长度。

Input示例

8
5
1
6
8
2
4
5
10

Output示例

5

刚开始以为这是一个简单的模板题,写了提交就T了。

附代码(TLE):

#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
int a[50001],dp[50001];
int main()
{
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
        scanf("%d",&a[i]);
    for(int i=1;i<=n;i++)
    {
        dp[i]=1;
        for(int j=1;j<i;j++)
        {
            if(a[j]<a[i])
                dp[i]=max(dp[i],dp[j]+1);
        }
    }
    sort(dp+1,dp+n+1);
    printf("%d\n",dp[n]);
    return 0;
}



后来百度了一下,有二分的方法来优化他,我们设置一个一维数组dp[i]来表示长度为i的最小末尾是dp[i]

就拿这组数据来说,

5 1 6 8 2 4 5 10

先把a[1]放在dp[1]中,长度为1的最小末尾为5,此时长度为1。dp[1]=5

a[2]<dp[1],此时就要更新长度为1的最小末尾。dp[1]=1

a[3]>dp[1],这是就要增加dp[len]的长度。dp[2]=6

a[4]>dp[2],dp[3]=8

a[5]<dp[3],a[5]应该在dp[1]-dp[3]之间,那么长度为2的最小末尾就是a[5]。dp[2]=2

a[6]<dp[3],同上,dp[3]=4

a[7]>dp[3],dp[4]=5

a[8]>dp[4],dp[5]=10;

len=5;

AC代码:

#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <queue>
#include <map>
using namespace std;
int dp[50001],a[50001];
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        int len=1;
        for(int i=1;i<=n;i++)
            scanf("%d",&a[i]);
        dp[len]=a[1];
        for(int i=2;i<=n;i++)
        {
            if(a[i]>dp[len])
                dp[++len]=a[i];
            else
            {
                int m=lower_bound(dp+1,dp+len+1,a[i])-dp;//返回大于a[i]的第一个元素的位置。
                dp[m]=a[i];
            }
        }
        printf("%d\n",len);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42217376/article/details/81261872