zoukankan      html  css  js  c++  java
  • 最长增长子序列 DP

    #include<iostream>
    using namespace std;
    #define INF 0x7fffffff
    #define N 10000
    
    // O(n^2)
    int len[N];
    int dp(int *a, int n){
        int mx = 0, mxlen = 1;
        for (int i = 0; i < n; ++i)
            len[i] = 1;
        for (int i = 1; i < n; ++i){
            mx = 0;
            for (int j = 0; j < i; ++j)        // 寻找len[0...i-1]最大值
                if (a[j]<a[i] && len[j]>mx)
                    mx = len[j];
            len[i] = mx + 1;
            if (mxlen < len[i]) mxlen = len[i];    // 更新最大长度
        }
        return mxlen;
    }
    
    // O(nlogn)
    int mv[N];    //mv[i]存放序列长度为 i+1 的最小元素
    int binarySearch(int r, int val)
    {
        int left = 0, right = r, mid;
        while (left < right){
            mid = (left + right) / 2;
            if (mv[mid] < val) left = mid + 1;
            else right = mid;
        }
        return left;
    }
    int binaryLIS(int *a, int n)
    {
        int len = 0;
        mv[0] = a[0];
        for (int i = 1; i < n; ++i){
            if (a[i]>mv[len]) mv[++len] = a[i];
            else mv[binarySearch(len, a[i])] = a[i];
            for (int i = 0; i < len; ++i)
                cout << mv[i] << ' ';
            cout << mv[len] << endl;
        }
        return len + 1;
    }
    
    int main()
    {
        int a[] = { 1, 7, 3, 5, 9, 4, 8 };
        cout << dp(a, 7) << endl;
        cout << binaryLIS(a, 7) << endl;
    }
  • 相关阅读:
    规矩与管理
    信息系统叫设施比叫工具更贴近本义
    让ansbile和docker愉快的在一起
    elasearch基础教程
    markdown语法
    python 实用pickle序列化
    python 解析配置文件
    ansible状态管理
    haproxy官方配置文档地址
    ansible操作模块相关
  • 原文地址:https://www.cnblogs.com/jokoz/p/4770728.html
Copyright © 2011-2022 走看看