-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathTrie 1.cpp
118 lines (118 loc) · 1.88 KB
/
Trie 1.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
struct Node
{
int cntL, cntR, lIdx, rIdx;
Node()
{
cntL = cntR = 0;
lIdx = rIdx = -1;
}
};
Node Tree[MAX];
int globalIdx = 0;
class Trie
{
public:
void insert(int val, int idx, int depth)
{
for (int i = depth - 1; i >= 0; i--)
{
bool bit = val & (1 << i);
// cout<<"bit now: "<<bit<<endl;
if (bit)
{
Tree[idx].cntR++;
if (Tree[idx].rIdx == -1)
{
Tree[idx].rIdx = ++globalIdx;
idx = globalIdx;
}
else idx = Tree[idx].rIdx;
}
else
{
Tree[idx].cntL++;
if (Tree[idx].lIdx == -1)
{
Tree[idx].lIdx = ++globalIdx;
idx = globalIdx;
}
else idx = Tree[idx].lIdx;
}
}
}
int query(int val, int compVal, int idx, int depth)
{
int ans = 0;
for (int i = depth - 1; i >= 0; i--)
{
bool valBit = val & (1 << i);
bool compBit = compVal & (1 << i);
if (compBit)
{
if (valBit)
{
ans += Tree[idx].cntR;
idx = Tree[idx].lIdx;
}
else
{
ans += Tree[idx].cntL;
idx = Tree[idx].rIdx;
}
}
else
{
if (valBit)
{
idx = Tree[idx].rIdx;
}
else
{
idx = Tree[idx].lIdx;
}
}
if (idx == -1) break;
}
return ans;
}
void clear()
{
for (int i = 0; i <= globalIdx; i++)
{
Tree[i].cntL = 0;
Tree[i].cntR = 0;
Tree[i].rIdx = -1;
Tree[i].lIdx = -1;
}
globalIdx = 0;
}
};
int main()
{
// ios_base::sync_with_stdio(0);
// cin.tie(NULL); cout.tie(NULL);
// freopen("in.txt","r",stdin);
// Given an array of positive integers you have to print the number of
// subarrays whose XOR is less than K.
int test, n, k, x;
Trie T;
scanf("%d", &test);
while (test--)
{
scanf("%d%d", &n, &k);
T.insert(0, 0, 20);
int pre = 0;
ll ans = 0;
FOR(i, 0, n)
{
scanf("%d", &x);
pre ^= x;
// prnt(pre);
ans += T.query(pre, k, 0, 20);
T.insert(pre, 0, 20);
}
printf("%lld\n", ans);
T.clear();
}
return 0;
}