POJ 2533-Longest Ordered Subsequence(裸题:最长上升子序列)

Longest Ordered Subsequence

Time Limit: 2000MS


Memory Limit: 65536K

Total Submissions: 60249


Accepted: 26983

Description

A numeric sequence of ai is ordered if a1 < a2 < ... < aN. Let the subsequence of the given numeric sequence (a1, a2, ..., aN) be any sequence (ai1, ai2, ..., aiK), where 1 <= i1 < i2 < ... < iK <= N. For example, sequence (1, 7, 3, 5, 9, 4, 8) has ordered subsequences, e. g., (1, 7), (3, 4, 8) and many others. All longest ordered subsequences are of length 4, e. g., (1, 3, 5, 8).

Your program, when given the numeric sequence, must find the length of its longest ordered subsequence.

Input

The first line of input file contains the length of sequence N. The second line contains the elements of sequence - N integers in the range from 0 to 10000 each, separated by spaces. 1 <= N <= 1000

Output

Output file must contain a single integer - the length of the longest ordered subsequence of the given sequence.

Sample Input

71 7 3 5 9 4 8

Sample Output

4

Source

Northeastern Europe 2002, Far-Eastern Subregion

解题思路:裸的最大上升子序列,下面给出O(n^n)和O(n*logn)的两种算法


O(n^n)的AC代码:
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<queue>
#include<map>
#include<set>
#define sa(a) scanf("%d", &a);
#define bug printf("--------");
using namespace std;
typedef long long LL;
const int INF = 1e9;
const int mod  = 1e9+7;

int n, a[1010], dp[1010];

int main()
{
    while(~scanf("%d", &n)) {
        int ans = 1;
        for(int i = 0; i < n; i ++) {
            scanf("%d", &a[i]);
            dp[i] = 1;
        }
        for(int i = 0; i < n-1; i ++) {
            for(int j = i; j >= 0; j --) { //完全的暴力向前搜索
                if(a[i+1] > a[j]) dp[i+1] = max(dp[i+1], dp[j]+1);
                ans = max(ans, dp[i+1]);
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}

O(n*logn)的AC代码:
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<math.h>
#include<stdlib.h>
#include<queue>
#include<map>
#define bug printf("--------");
using namespace std;
typedef long long LL;
const int INF = 1e9;

int n, a[1010] ,dp[1010], ans;

//upper_bound(a, a+n, x)的作用:返回a[0]~a[n-1]中第一个>x的a[i]的地址
//lower_bound(a, a+n, x)的作用:返回a[0]~a[n-1]中第一个>=x的a[i]的地址

int main()
{
    while(~scanf("%d", &n)) {
        ans = 0;
        fill(dp, dp+n, INF); //我们需要先对dp进行初始化
        for(int i = 0; i <n; i ++)
            scanf("%d", &a[i]);
        for(int i = 0; i < n; i ++) {
            *upper_bound(dp, dp+n, a[i]) = a[i]; //修改该位置的值
            //有点类似正向迭代器
            //对于样例自己插入模拟下就懂了
            ans = max(ans, upper_bound(dp, dp+n, a[i]) - dp); //返回长度,并更新最大长度
        }
        printf("%d\n", ans);
    }
    return 0;
}

//上面这个可以当作板子用,对于不同的题目进行修改就可以了

猜你喜欢

转载自blog.csdn.net/i_believe_cwj/article/details/80223761