最长上升子序列

O(nlogn)算法:不能得到序列本身

贪心思想,同样是长度为tot的最长上升子序列,结尾的数字越小对后面的选择越有利,所以若以a[i]结尾的最长上升子序列长为tot, a[j]结尾也是这样,且j>i&&a[i]>a[j],就用a[j]替换a[i],正确性自证

#include <bits/stdc++.h>

using namespace std;
int d[1005],f[1005];
int main()
{
    int n,u, top=0;
    scanf("%d%d",&n,&u);

    d[0] = d[++top] = u;
    f[1] = 1;
    for(int i = 2; i <= n; i++){
        int u;
        scanf("%d",&u);
        if(u > d[top])d[++top] = u, f[i] = top;
        else{
            int pos = lower_bound(d + 1, d + 1 + top, u) - d;
            d[pos] = u, f[i] = pos;
        }
    }
    printf("%d
",top);
    for(int i = 1; i <= n; i++)printf("%d ", f[i]);
    return 0;
}
原文地址:https://www.cnblogs.com/EdSheeran/p/8459847.html