最長上升子序列 nlogn

最長上升子序列中對於數ipt[i],向前遍歷,當數ipt[j]小於ipt[i] 則ipt[j]可作爲上升序列中ipt[i]的前一個數字

dp[i] = max{ dp[j] + 1 | j < i && ipt[j] < ipt[i]}


若現在有兩個狀態a,b 滿足dp[a] = dp[b]且 ipt[a] < ipt[b] 

則對於後面的狀態dp[a]更優  因爲若ipt[i] > dp[b] 則必然ipt[i] > dp[a],反之若ipt[i] > dp[a] 卻不一定滿足ipt[i] > dp[b]

所以若只保存狀態a  那麼也不會丟失最優解 

那麼對於相同dp值,只需保留ipt最小的一個

則  ipt值(dp=1) < ipt值(dp=2) < ipt值(dp=3).....

即此序列有序 

比如  1 6 2 3 7 5  

   dp  1 2 2 3 4 4 

當計算2時  發現dp=2的ipt值爲6  則6可替換爲2

同理    1 (6) 2 3 (7) 5

     dp 1      2 3      4

這樣,計算時維護一個序列即可


//#pragma comment(linker, "/STACK:102400000,102400000")
//HEAD
#include <cstdio>
#include <cstring>
#include <vector>
#include <iostream>
#include <algorithm>

#include <queue>
#include <string>
#include <set>
#include <stack>
#include <map>
#include <cmath>
#include <cstdlib>

using namespace std;
//LOOP
#define FE(i, a, b) for(int i = (a); i <= (b); ++i)
#define FED(i, b, a) for(int i = (b); i>= (a); --i)
#define REP(i, N) for(int i = 0; i < (N); ++i)
#define CLR(A,value) memset(A,value,sizeof(A))
//STL
#define PB push_back
//INPUT
#define RI(n) scanf("%d", &n)
#define RII(n, m) scanf("%d%d", &n, &m)
#define RIII(n, m, k) scanf("%d%d%d", &n, &m, &k)
#define RS(s) scanf("%s", s)
typedef long long LL;
const int INF = 0x3f3f3f3f;
const int MAXN = 1010;


#define FF(i, a, b) for(int i = (a); i < (b); ++i)
#define FD(i, b, a) for(int i = (b) - 1; i >= (a); --i)
#define CPY(a, b) memcpy(a, b, sizeof(a))
#define FC(it, c) for(__typeof((c).begin()) it = (c).begin(); it != (c).end(); it++)
#define EQ(a, b) (fabs((a) - (b)) <= 1e-10)
#define ALL(c) (c).begin(), (c).end()
#define SZ(V) (int)V.size()
#define RIV(n, m, k, p) scanf("%d%d%d%d", &n, &m, &k, &p)
#define RV(n, m, k, p, q) scanf("%d%d%d%d%d", &n, &m, &k, &p, &q)
#define WI(n) printf("%d\n", n)
#define WS(s) printf("%s\n", s)
#define sqr(x) (x) * (x)
typedef vector <int> VI;
typedef unsigned long long ULL;
const double eps = 1e-10;
const LL MOD = 1e9 + 7;

int ipt[1010], dp[1010], a[1010];

int main()
{
    int n;
    while (~RI(n))
    {
        REP(i, n)
            RI(ipt[i]);
        REP(i, n)   dp[i] = 1;
        int ans = 0;
        CLR(a, INF);
        REP(i, n)
        {
            int x = lower_bound(a, a + ans, ipt[i]) - a;
            dp[i] =  x + 1;
            ans = max(ans, dp[i]);
            a[x] = ipt[i];
        }
        cout << ans << endl;
    }
    return 0;
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章