最长增子列优化算法

#include <iostream>//一个更加形象的代码,不仅求出最大长度,同时用二维数组存储每个阶段的最长子序列
#include <vector>
#include <stack>
#include <algorithm>
using namespace std;
void newpush(vector<vector<int>> &ans,int cur) {
    vector<int> tmp;
    int f = 0;
    if (ans.empty()) {
        tmp.push_back(cur);
        ans.push_back(tmp);
        return;
    }
    for (int i = 0; i < ans.size();i++) {
        if (ans[i][ans[i].size() - 1]<cur) {
            ans[i].push_back(cur);
            f = 1;
        }
    }
    if (f == 0) {
        tmp.push_back(cur);
        ans.push_back(tmp);
    }
    return;
}
int main(void) {
    int n;
    while (cin >> n) {
        vector<int> num(n);
        for (int i = 0; i < n;i++) {
            cin >> num[i];
        }
        vector<vector<int>> ans;
        for (int i = 0; i < n;i++) {
            newpush(ans, num[i]);
        }
        int mindex = 0, max = ans[mindex].size();
        for (int i = 0; i < ans.size(); i++) {
            if (ans[i].size() > max) {
                max = ans[i].size();
                mindex = i;
            }
        }
        for (int i = 0; i < ans[mindex].size();i++) {
            cout << ans[mindex][i] << ' ';
        }
        cout << endl;
        cout <<max<< endl;
    }
    return 0;
}
===================================================================================================================
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(void) {
    int n;    
    while (cin >> n) {
        int m = 1;
        vector <int> a(n), dq(n);
        for (int i = 0; i < n ; i++) {
            cin >> a[i];
            dq[i] = 1;
            for (int j = 0; j < i; j++) {
                if (a[i] > a[j])dq[i] = max(dq[i], dq[j] + 1);
            }
            if (dq[i] > m)m = dq[i];
        }
        cout << m << endl;
    }
    return 0;
}
posted @ 2021-11-18 20:08  Zupernova  阅读(25)  评论(0编辑  收藏  举报