51nod1134最长递增子序列

http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1134

给出长度为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

暴力一下不能过........

#include <iostream>  
#include <string.h>  
#include <algorithm>  
#include <stdio.h>  
#include <math.h>  
#include <bitset>  
using namespace std; 
int dp[50005]; 
int a[50005];
int main()  
{  
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    cin>>a[i];
    int ans=0;
    for(int i=0;i<n;i++)
    dp[i]=1;
    for(int i=1;i<n;i++)
    {
    	for(int j=0;j<i;j++)
    	{
    		if(a[i]>a[j])
    		dp[i]=max(dp[i],dp[j]+1);
    	}
    	ans=max(ans,dp[i]);
    }
 	cout<<ans<<endl;
    return 0;  
}  

后来只能在网上找大牛的博客学会了lower-bound函数:https://www.cnblogs.com/is-Tina/p/7294067.html

#include <iostream>  
#include <string.h>  
#include <algorithm>  
#include <stdio.h>  
#include <math.h>  
#include <bitset>  
using namespace std; 
int dp[50005]; 
int a[50005];
int main()  
{  
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    cin>>a[i];
    int ans=1;
    memset(dp,0,sizeof(dp));
    dp[0]=a[0];
    for(int i=1;i<n;i++)
    {
    	int pos=lower_bound(dp,dp+ans,a[i])-dp;//查找大于a[i]的位置   -dp返回最初位置 
    	dp[pos]=a[i];//一直更新数值 
    	ans=max(ans,pos+1);//记录最大值 
    }
 	cout<<ans<<endl;
    return 0;  
}  

猜你喜欢

转载自blog.csdn.net/qq_41453511/article/details/81146153
今日推荐