POJ - 3903S tock Exchange 最长上升子序列 +二分查找

题目描述

给定一个序列, 求他的最长上升子序列

样例

Sample Input
6 
5 2 1 4 5 3 
3  
1 1 1 
4 
4 3 2 1
Sample Output
3 
1 
1

思路
由于数据范围很大, 不能用O(n^2)扫描的方法,会TLE
O(n^2)代码

#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int map[100010];
int dp[100010]; 

int main(){
	int n;
	cin >> n;
	for(int i = 1; i <= n; i++){
		scanf("%d", &map[i]);
		dp[i] = 1;
	}
	for(int i = 1; i <= n; i++){
		for(int j = i - 1; j > 0; j--){
			if(map[i] > map[j]) dp[i] = max(dp[i], dp[j] + 1);
		}	
	}
	int maxx = -1;
	for(int i = 1; i <= n; i++){
		maxx = max(dp[i], maxx);
	}
	cout << maxx << endl;
	return 0;
} 

我们这里用在DP数组中更新存入上升子序列的方法,用二分查找前面已经存入DP数组中第一个大于a[I]的数把它更新,时间复杂度降为O(N*logN)
代码

#include<iostream>
#include<cstdio>
using namespace std;
const int N = 100010;
int f[N], a[N];
int n;
int main(){
    while(scanf("%d", &n) != EOF){
        for(int i = 1; i <= n; i++) cin >>  a[i];
        int cnt = 1;
        f[cnt++] = a[1];
        for(int i = 2; i <= n; i++){
            if(a[i] > f[cnt - 1]) f[cnt++] = a[i];
            else{
                int l = 1; 
                int r = cnt - 1;
                while(l < r){
                    int mid = (l + r ) >> 1;
                    if(f[mid] >= a[i]) r = mid;
                    else l = mid + 1;
                }
                f[r] = a[i];
            }
        }
        cout << cnt - 1  << endl;
    }
    return 0;
}
发布了54 篇原创文章 · 获赞 155 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_45432665/article/details/104174376