D2. Xor-Subsequence (hard version)
time limit per test
2 seconds
memory limit per test
512 megabytes
input
standard input
output
standard output
It is the hard version of the problem. The only difference is that in this version ai≤109ai≤109.
You are given an array of nn integers a0,a1,a2,…an−1a0,a1,a2,…an−1. Bryap wants to find the longest beautiful subsequence in the array.
An array b=[b0,b1,…,bm−1]b=[b0,b1,…,bm−1], where 0≤b0<b1<…<bm−1<n0≤b0<b1<…<bm−1<n, is a subsequence of length mm of the array aa.
Subsequence b=[b0,b1,…,bm−1]b=[b0,b1,…,bm−1] of length mm is called beautiful, if the following condition holds:
- For any pp (0≤p<m−10≤p<m−1) holds: abp⊕bp+1<abp+1⊕bpabp⊕bp+1<abp+1⊕bp.
Here a⊕ba⊕b denotes the bitwise XOR of aa and bb. For example, 2⊕4=62⊕4=6 and 3⊕1=23⊕1=2.
Bryap is a simple person so he only wants to know the length of the longest such subsequence. Help Bryap and find the answer to his question.
Input
The first line contains a single integer tt (1≤t≤1051≤t≤105) — the number of test cases. The description of the test cases follows.
The first line of each test case contains a single integer nn (2≤n≤3⋅1052≤n≤3⋅105) — the length of the array.
The second line of each test case contains nn integers a0,a1,...,an−1a0,a1,...,an−1 (0≤ai≤1090≤ai≤109) — the elements of the array.
It is guaranteed that the sum of nn over all test cases does not exceed 3⋅1053⋅105.
Output
For each test case print a single integer — the length of the longest beautiful subsequence.
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=9e6+5;
int tr[N][2],f[N][2],idx;
int dp[N],a[N];
void insert(int n,int k)
{
int root=0;
for(int i=30;i>=0;i--)
{
int now=(n>>i)&1;
if(tr[root][now]) root=tr[root][now];
else root=tr[root][now]=++idx;
f[root][(k>>i)&1]=max(f[root][(k>>i)&1],dp[k]);
}
}
int query(int n,int k)
{
int root=0,res=1;
for(int i=30;i>=0;i--)
{
int now=(n>>i)&1;
int rev=tr[root][now^1];
if(rev) res=max(res,f[rev][(k>>i)&1^1]+1);
root=tr[root][now];
if(!root) break;
}
return res;
}
void solve()
{
idx=0;
int n;cin>>n;
for(int i=0;i<n;i++) cin>>a[i],dp[i]=1;
int mx=0;
for(int i=0;i<n;i++)
{
dp[i]=query(a[i]^i,a[i]);
insert(a[i]^i,i);
mx=max(mx,dp[i]);
}
cout<<mx<<'\n';
for(int i=0;i<=idx;i++) f[i][0]=f[i][1]=tr[i][0]=tr[i][1]=0;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
int t;cin>>t;
while(t--)
{
solve();
}
}