[POJ 2533]Longest Ordered Subsequence[LIS]

题目链接: [POJ 2533]Longest Ordered Subsequence[LIS]

题意分析:

求单调递增的最长上升子序列。

解题思路:

n^2:dp[i]代表,以i结尾的最长上升子序列,那么dp[i] = max(dp[i], dp[j] + 1) (j: 0 ~ i)

nlogn:dp[i],dp[i]代表长度为i的子序列对应的最末位元素。

个人感受:

n^2差点被坑死= =,最后忘记for循环一遍。nlog比n^2好写多了,2333

具体代码如下:

n^2:

#include<algorithm>
#include<cctype>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iomanip>
#include<iostream>
#include<map>
#include<queue>
#include<set>
#include<sstream>
#include<stack>
#include<string>
#define pr(x) cout << #x << " = " << (x) << '\n';
using namespace std;

const int MAXN = 1e3 + 111;

int a[MAXN], dp[MAXN];

int main()
{
    int n;
    cin >> n;
    for (int i = 1; i <= n; ++i) cin >> a[i];

    int ans = 0;
    for (int i = 1; i <= n; ++i) {
        dp[i] = 1;
        for (int j = 1; j < i; ++j) {
            if (a[i] > a[j])
                dp[i] = max(dp[i], dp[j] + 1);
        }
        ans = max(ans, dp[i]);
    }
    cout << ans << '\n';
    return 0;
}


nlogn:

#include<algorithm>
#include<cctype>
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iomanip>
#include<iostream>
#include<map>
#include<queue>
#include<set>
#include<sstream>
#include<stack>
#include<string>
#define pr(x) cout << #x << " = " << (x) << '\n';
using namespace std;

const int MAXN = 1e3 + 111;

int a[MAXN], dp[MAXN];

int main()
{
    int n;
    cin >> n;
    for (int i = 1; i <= n; ++i) cin >> a[i];

    memset(dp, 0x3f, sizeof dp);
    for (int i = 1; i <= n; ++i) {
        int x = lower_bound(dp, dp + n, a[i]) - dp;
        dp[x] = a[i];
    }
    cout << lower_bound(dp, dp + n, 0x3f3f3f3f) - dp << '\n';
    return 0;
}


你可能感兴趣的:(dp)