Xor-Subsequence (hard version)(字典树上dp)

//https://codeforces.com/contest/1720/problem/D2
#include <bits/stdc++.h>
#define ll long long
#define all(a) a.begin(), a.end()
#define IOS ios::sync_with_stdio(false), cin.tie(0), cout.tie(0);
using namespace std;
const int N = 3e5 + 10;

int tot = 0;
struct node
{
    int ch[2];
    int dp[2][2];
} tree[N * 31];

int newNode()
{
    tot++;
    memset(tree[tot].ch, 0, sizeof tree[tot].ch);
    memset(tree[tot].dp, 0, sizeof tree[tot].dp);
    return tot;
}

void insert(int x, int y, int val)
{
    int p = 0;
    for (int i = 29; i >= 0; i--)
    {
        int a = x >> i & 1;
        int b = y >> i & 1;
        tree[p].dp[a][b] = max(tree[p].dp[a][b], val);
        if(tree[p].ch[a ^ b] == 0)
            tree[p].ch[a ^ b] = newNode();
        p = tree[p].ch[a ^ b];
    }
}

int query(int x, int y, int i, int p)
{
    if (i < 0)
        return 1;
    int mx = 1;
    int a = x >> i & 1;
    int b = y >> i & 1;
    for (int j = 0; j < 2; j++)
        for (int k = 0; k < 2; k++)
            if ((k ^ a) < (j ^ b))
                mx = max(mx, tree[p].dp[j][k] + 1);
    if (tree[p].ch[a ^ b])
        mx = max(mx, query(x, y, i - 1, tree[p].ch[a ^ b]));
    return mx;
}

void solve()
{
    int n;
    cin >> n;
    vector<int> a(n);
    for (int i = 0; i < n; i++)
        cin >> a[i];

    tot = 0;
    memset(tree[tot].ch, 0, sizeof tree[tot].ch);
    memset(tree[tot].dp, 0, sizeof tree[tot].dp);
    int ans = 0;
    for (int i = 0; i < n; i++)
    {
        int val = query(i, a[i], 29, 0);
        // cerr << "??? " << i << ' ' << val << '\n';
        insert(i, a[i], val);
        ans = max(ans, val);
    }

    cout << ans << '\n';
}

signed main()
{
    IOS;
    int t = 1;
    cin >> t;
    while (t--)
        solve();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值