SCPJ2024 D

· · 题解

线段树学傻了。

简化题意

求最长的子序列 b,使得 b_1=b_2,b_3=b_4\dots b_{|b|-1}=b{|b|} 且 b_2\neq b_3,b_4\neq b_5\dots b_{|b|-2}\neq b_{|b|-1}。

朴素dp

设 f_i 为以 a_i 结尾的长度为偶数的答案,g_i 为结尾元素值为 i 的长度为奇数的答案,则有:

f_i= \begin{cases} g_{a_i}+1 && g_{a_i}\neq 0 \\ 0 && \text{otherwise} \end{cases} g_i= \max_{j=1}^{5\times10^5}f_j(j\neq a_i)

优化

把 f 按照 a_i 丢进线段树里即可。

#include<bits/stdc++.h>
using namespace std;
#define N 500005
int f[N], g[N], n, a[N];
#define reg
int tr[N << 2], P;
void update(reg int x, int v) {
    x += P;tr[x] = v;
    while((x /= 2, x))
        tr[x] = max(tr[x * 2], tr[x * 2 + 1]);
}
int query(reg int l, reg int r) {
    if(l > r) return 0;
    reg int mx = 0;
    for(l = P + l - 1, r = P + r + 1;l ^ r ^ 1;l /= 2, r /= 2) {
        if(!(l & 1))
            mx = max(mx, tr[l ^ 1]);
        if(r & 1)
            mx = max(mx, tr[r ^ 1]);
    }
    return mx;
}
signed main() {
    //freopen("pairing4.in", "r", stdin);
    ios::sync_with_stdio(0);
    cin.tie(0), cout.tie(0);
    cin >> n;
    int mx = 0;
    for(int i = 1;i <= n;i ++) cin >> a[i], mx = max(a[i], mx);
    P = 1;
    while(P <= mx)
        P = P << 1;
    int ans = 0;
    for(int i = 1;i <= n;i ++) {
        f[i] = g[a[i]] ? g[a[i]] + 1 : 0;
        g[a[i]] = max(query(1, a[i] - 1), query(a[i] + 1, mx)) + 1;
        update(a[i], f[i]);
        ans = max(ans, f[i]);
    }
    cout << ans;
}