1. 程式人生 > 其它 >LIS最長上升子序列模板

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; }