LIS最长上升子序列模板

#include <bits/stdc++.h>
using namespace std;
const int N = 1009;
int n;
int a[N], f[N];
signed main()
{
    ios::sync_with_stdio(false);
    cin >> n;
    for(int i = 1; i <= n; i++) cin >> a[i];
    for(int i = 1; i <= n; i++)
    {
        f[i] = 1;
        for(int j = 1; j < i; j++)
        {
            if(a[j] < a[i]) f[i] = max(f[i], f[j] + 1);
        }
    }
    int res = 0;
    for(int i = 1; i <= n; i++) res = max(res, f[i]);
    cout << res;
    return 0;
}
/**\
二分+贪心优化
\**/
#include <bits/stdc++.h>
using namespace std;
const int N = 100010;
int n, a[N], low[N], ans;

//二分出low[i]中第一个大于等于x 的值的位置 y总模板不解释
int bs1(int a[], int maxx, int x)
{
    int l = 1, r = maxx;
    while(l < r)
    {
        int mid = (l + r) >> 1;
        if(a[mid] >= x) r = mid;
        else l = mid + 1;
    }
    return l;
}
signed main()
{
    ios::sync_with_stdio(false);
    cin >> n;
    for(int i = 1; i <= n; i++) cin >> a[i];

    //low[i] 代表 以长度为 i 结尾元素的最小值
    low[1] = a[1];
    ans++;

    for(int i = 2; i <= n; i++)
    {
        if(a[i] > low[ans])   low[++ans] = a[i];
        else
        {
            low[bs1(low, ans, a[i])] = a[i];
        }
    }
    cout << ans;
    return 0;
}

 

posted @ 2022-03-09 10:58  std&ice  阅读(46)  评论(0编辑  收藏  举报