hdu 5269 ZYB loves Xor I(字典树)

时间:2021-02-26 01:48:54

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5269

思路分析:当lowbit(AxorB)=2p 时,表示A与B的二进制表示的0-p-1位相等,第p位不同;考虑维护一棵字母树,将所有数字

转换为二进制形式并且从第0位开始插入树中,并在每个节点中记录通过该结点的数字数目;最后统计答案,对于每一个数字,

对于在其路径中的每一个结点X,假设其为第K层,统计通过与该结点不同的值的结点的数目count,则结果增加count*2k;

代码如下:

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std; const int MAX_N = * + ;
int num[MAX_N];
struct Node{
Node *child[];
int count;
Node(){
count = ;
memset(child, , sizeof(child));
}
Node(int value){
count = value;
memset(child, , sizeof(child));
}
}; void Insert(Node *head, int value){
Node *pre = head, *next = NULL;
for (int i = ; i < ; ++ i){
if (pre->child[value & ] == NULL){
pre->child[value & ] = new Node();
pre = pre->child[value & ];
}else{
next = pre->child[value & ];
next->count++;
pre = next;
}
value >>= ;
}
} void MakeEmpty(Node *node){
node->count = ;
if (node->child[])
MakeEmpty(node->child[]);
if (node->child[])
MakeEmpty(node->child[]);
} long long Query(Node *head, int value){
Node *pre = head, *next = NULL, *other;
long long ret = ; for (int i = ; i < ; ++ i){
next = pre->child[value & ];
other = pre->child[(value & ) ^ ];
if (other)
ret = (ret + other->count * ( << i)) % ;
pre = next;
value >>= ;
}
return ret;
} int main(){
int case_times, n;
int case_id = ; scanf("%d", &case_times);
while (case_times--){
Node *head = new Node(); scanf("%d", &n);
for (int i = ; i < n; ++i){
scanf("%d", &num[i]);
Insert(head, num[i]);
} long long ans = ;
for (int i = ; i < n; ++i)
ans = (ans + Query(head, num[i])) % ;
MakeEmpty(head);
printf("Case #%d: %I64d\n", ++case_id, ans);
}
return ;
}