码迷,mamicode.com
首页 > 其他好文 > 详细

最长上升子序列

时间:2017-12-11 21:11:52      阅读:181      评论:0      收藏:0      [点我收藏+]

标签:def   pos   cpp   mes   one   str   max   order   连接   

是一道简单的最长上升子序列问题
用下面的dp代码就可以轻松解决。
技术分享图片
 1 #include <cstdio>
 2 #include <cstring>
 3 #include <algorithm>
 4 
 5 using namespace std;
 6 
 7 int dp[1005],num[1005];
 8 
 9 int main()
10 {
11     int n,ans;
12     scanf("%d",&n);
13     ans=0;
14     for(int i=0;i<n;i++)
15     {
16         scanf("%d",&num[i]);
17         dp[i]=1;
18         for(int j=0;j<i;j++)
19         {
20             if(num[i]>num[j])
21                 dp[i]= dp[i] > dp[j]+1 ? dp[i] :dp[j]+1;
22         }
23         ans=dp[i] >ans ? dp[i] :ans;
24     }
25     printf("%d\n",ans);
26     return 0;
27 }
View Code
 
相同类型的问题
https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1134
这个连接上的最长递增子序列问题用上面的代码就会TLE
因为这个题目的数据不小,没有优化的dp就很容易T掉
 
下面给出优化后的代码
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <stdlib.h>
#include <iostream>
#define inf 0x3f3f3f3f
#define Max 1000500
using namespace std;
int dp[Max],a[Max];

void solve(int n)
{
    for(int i=0;i<n;i++)
    {
        dp[i]=inf;
    }
    for(int i=0;i<n;i++)
    {
        *lower_bound(dp,dp+n,a[i])=a[i];///返回一个指针
    }

    printf("%d\n",lower_bound(dp,dp+n,inf)-dp);
}

int main()
{
    int n;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
        scanf("%d",&a[i]);
    solve(n);
    return 0;
}

 

最长上升子序列

标签:def   pos   cpp   mes   one   str   max   order   连接   

原文地址:http://www.cnblogs.com/zhangzehua/p/8024879.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!