BZOJ3173 TJOI2013最長上升子序列(Treap+ZKW線段樹)

傳送門

Description

給定一個序列,初始爲空。現在我們將1到N的數字插入到序列中,每次將一個數字插入到一個特定的位置。每插入一個數字,我們都想知道此時最長上升子序列長度是多少?

Input

第一行一個整數N,表示我們要將1到N插入序列中,接下是N個數字,第k個數字Xk,表示我們將k插入到位置Xk(0<=Xk<=k-1,1<=k<=N)

Output

N行,第i行表示i插入Xi位置後序列的最長上升子序列的長度是多少。

Sample Input

3
0 0 2

Sample Output

1
1
2

HINT

100%的數據 n<=100000

因爲每一次加進來的都是最大的值,所以是不會更新其他的答案的,所以我們可以先把序列搞出來,離線亂搞搞就好了,沒事就試了一下zkw線段樹,發現還挺快的,不過還是要比樹狀數組慢不少。

/**************************************************************
    Problem: 3173
    User: geng4512
    Language: C++
    Result: Accepted
    Time:644 ms
    Memory:4712 kb
****************************************************************/

#include<cstdio>
#define MAXN 100005
struct node { int c[2], sz, rnd; } t[MAXN];
unsigned sd = 2333;
int Sz, a[MAXN], cnt, n, rt, mx[MAXN<<2], M, ans[MAXN];
inline int Max(int a, int b) { return a > b ? a : b; }
inline void GET(int &n) {
    n = 0; char c;
    do c = getchar(); while('0' > c || c > '9');
    do n = n * 10 + c - '0', c = getchar(); while('0' <= c && c <= '9');
}
inline unsigned Ran() { return sd = sd * sd + 12580; }
inline void Upd(int k) { t[k].sz = t[t[k].c[0]].sz + t[t[k].c[1]].sz + 1; }
inline void Rot(int &k, bool f) {
    int tmp = t[k].c[f]; t[k].c[f] = t[tmp].c[!f]; t[tmp].c[!f] = k;
    Upd(k); Upd(tmp); k = tmp;
}
void Insert(int &k, int sz) {
    if(!k) { k = ++ Sz; t[k].sz = 1; t[k].rnd = Ran(); return; }
    ++ t[k].sz;
    bool f = t[t[k].c[0]].sz < sz;
    Insert(t[k].c[f], sz - (t[t[k].c[0]].sz+1)*f);
    if(t[k].rnd > t[t[k].c[f]].rnd) Rot(k, f);
}
void dfs(int u) {
    if(!u) return;
    dfs(t[u].c[0]);
    a[++ cnt] = u;
    dfs(t[u].c[1]);
}
namespace Seg {
    void Insert(int x, int v) {
        for(mx[x += M] = v, x >>= 1; x; x >>= 1)
            mx[x] = Max(mx[x<<1], mx[x<<1|1]);
    }
    int Query(int r) {
        int ans = 0; 
        for(r += M + 1; r ^ 1; r >>= 1)
            if(r & 1) ans = Max(ans, mx[r^1]);
        return ans;
    }
}
int main() {
    GET(n); int t;
    for(int i = 1; i <= n; ++ i) {
        GET(t);
        Insert(rt, t);
    }
    dfs(rt);
    for(M = 1; M < n + 2; M <<= 1);
    for(int i = 1, tmp; i <= n; ++ i) {
        tmp = Seg::Query(a[i]) + 1;
        Seg::Insert(a[i], tmp);
        ans[a[i]] = tmp;
    }
    for(int i = 1; i <= n; ++ i) {
        ans[i] = Max(ans[i], ans[i-1]);
        printf("%d\n", ans[i]);
    }
    return 0;
}

發佈了116 篇原創文章 · 獲贊 24 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章