POJ 3903 Stock Exchange 【最长上升子序列】模板题

<题目链接>

题目大意:

裸的DP最长上升子序列,给你一段序列,求其最长上升子序列的长度,n^2的dp朴素算法过不了,这里用的是nlogn的算法,用了二分查找。

O(nlogn)算法

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int N= 1e5+5;
int a[N],rise[N];

int main(){
    int n;while(~scanf("%d",&n)){
        memset(rise,0,sizeof(rise));
        for(int i=0;i<n;i++)scanf("%d",&a[i]);
        int len=0;
        rise[0]=-1e9;
        for(int i=0;i<n;i++){
            if(a[i]>rise[len])rise[++len]=a[i];
            else{
                int j=lower_bound(rise+1,rise+1+len,a[i])-rise;
                rise[j]=a[i];
            }
        }
        printf("%d\n",len);
    }
}

 

 

虽然(n^2)算法过不了此题,但是还是放一下

 

#include <bits/stdc++.h>
using namespace std;

const int N = 1e5+5;
int n,dp[N],a[N];
//dp[i]表示以第i个元素为结尾的最长上升子序列长度

int main(){
    while(scanf("%d",&n)!=EOF){
        for(int i=0;i<n;i++) scanf("%d",&a[i]);
        dp[0]=1;
        for(int i=1;i<n;i++){
            dp[i]=1;
            for(int j=0;j<i;j++){
                if(a[j]<a[i] && dp[i]<dp[j]+1 ) dp[i]=dp[j]+1;
            }
        }
        int mx=-1e9;
        for(int i=0;i<n;i++) mx=max(mx,dp[i]);
        printf("%d\n",mx);
    }
}

 

posted @ 2018-04-29 10:11  悠悠呦~  阅读(208)  评论(0编辑  收藏  举报
浏览器标题切换
浏览器标题切换end