SUBXOR - SubXor
A straightforward question. Given an array of positive integers you have to print the number of subarrays whose XOR is less than K.
Subarrays are defined as a sequence of continuous elements Ai, Ai+1, ..., Aj . XOR of a subarray is defined as Ai^Ai+1^ ... ^Aj.
Symbol ^ is Exclusive Or. You can read more about it here:
http://en.wikipedia.org/wiki/Exclusive_or
Input Format:
First line contains T, the number of test cases. Each of the test case consists of N and K in one line, followed by N space separated integers in next line.
Output Format:
For each test case, print the required answer.
Constraints:
1 ≤ T ≤ 10
1 ≤ N ≤ 10^5
1 ≤ A[i] ≤ 10^5
1 ≤ K ≤ 10^6
Sum of N over all testcases will not exceed 10^5.
Sample Input:
1
5 2
4 1 3 2 7
Sample Output:
3
问题概述:给你一个长度为n的整数序列和一个k,问这个序列中有多少子串的异或和<k(一个子串ai,ai+1……aj的
异或和指的是ai^ai+1^……^aj)
https://vjudge.net/contest/145297#problem/D
异或性质:
①:a^b==c,那么a^c==b
②:a^b^b==a
解题步骤:
①:求出所有异或前缀和b[i]
②:枚举每一个b[i],对于当前b[i],将b[i-1]加入01字典树(注意如果当前是b[1],将"b[0]==0"加入字典树),之后
查询字典树找到满足b[j]^b[i]<k(0<j<i)的有多少个,最后将结果加在一起即可
字典树怎么建?
每个节点存储一个sum值,表示b[]中对应前缀数量(即有多少个b[j]在加入字典树时经过了这个节点)
怎么查询?
①:尽可能找到一条路径x,使得x^b[i]==k,到某个节点无法往下走了就直接返回ans
②:寻找的过程中如果k的对应位是1那么ans += sum[p],其中p^b[i]==0,p为节点上的数值(0or1)<<(最高位-树深)
#include<stdio.h>
#include<string.h>
typedef struct Trie
{
int sum;
Trie *next[2];
}Trie;
int k, a[100005], b[100005], vc[25];
void Create(Trie *root, int a)
{
int now, i;
Trie *p = root;
for(i=24;i>=0;i--)
{
now = 0;
if(a&(1<<i))
now = 1;
if(p->next[now]==NULL)
{
Trie *temp = new Trie;
temp->next[0] = temp->next[1] = NULL;
temp->sum = 0;
p->next[now] = temp;
}
p = p->next[now];
p->sum++;
}
}
int Query(Trie *root, int a)
{
int now, i, ans;
ans = 0;
Trie *p = root;
for(i=24;i>=0;i--)
{
now = 0;
if(a&(1<<i))
now = 1;
if(vc[i]==1)
{
if(p->next[!(1^now)]!=NULL)
ans += p->next[!(1^now)]->sum;
}
if(p->next[vc[i]^now]==NULL)
return ans;
p = p->next[vc[i]^now];
}
return ans;
}
void Delete(Trie *root)
{
if(root->next[0])
Delete(root->next[0]);
if(root->next[1])
Delete(root->next[1]);
delete root;
}
int main(void)
{
int T, i, n, k;
long long ans;
scanf("%d", &T);
while(T--)
{
Trie *root = new Trie;
root->next[0] = root->next[1] = NULL;
root->sum = 0;
ans = 0;
scanf("%d%d", &n, &k);
for(i=1;i<=n;i++)
{
scanf("%d", &a[i]);
b[i] = b[i-1]^a[i];
}
memset(vc, 0, sizeof(vc));
for(i=24;i>=0;i--)
{
if(k&(1<<i))
vc[i] = 1;
}
for(i=1;i<=n;i++)
{
Create(root, b[i-1]);
ans += Query(root, b[i]);
}
printf("%lld\n", ans);
Delete(root);
}
return 0;
}