hdu5269 ZYB loves Xor I (字典树)

Memphis loves xor very musch.Now he gets an array A.The length of A is n.Now he wants to know the sum of all (lowbit(AiAi xor AjAj)) (i,j∈[1,n])(i,j∈[1,n])
We define that lowbit(x)=2k2k,k is the smallest integer satisfied ((xx and 2k2k)>0)
Specially,lowbit(0)=0
Because the ans may be too big.You just need to output ansans mod 998244353
Input
Multiple test cases, the first line contains an integer T(no more than 10), indicating the number of cases. Each test case contains two lines
The first line has an integer nn
The second line has nn integers A1A1,A2A2….AnAn
n∈[1,5∗104]n∈[1,5∗104],Ai∈[0,229]Ai∈[0,229]
Output
For each case, the output should occupies exactly one line. The output format is Case #x: ans, here x is the data number begins at 1.
Sample Input
2
5
4 0 2 7 0
5
2 6 5 4 0
Sample Output
Case #1: 36
Case #2: 40

分析:lowbit(x)就是求x的最低位1转换成10进制的值,而 lowbit(xy)=2p 则表示x和y转化成二进制后,后p-1位是相同的
为了保证每次查询时,最后p-1位相同,插入字典树时要将 数的二进制 倒着插,这样可以保证每次查找时,前面的p-1位是相同的,既然前面都相同了,后面只需要记录一下不同的情况,然后乘上对应的二进制1即可
最后得出的答案要乘2,因为算出的只是x⊕y,y⊕x没有计算,乘2即可
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int mod=998244353;
struct node
{
    ll num;
    node *next[2];
    node ()
    {
        next[0]=next[1]=NULL;
        num=0;
    }
};
node *root;
void trie_add(ll num)
{
    node *p=root;
    for(ll i=0;i<=30;i++)
    {
        int x=num%2;
        num/=2;
        if(p->next[x]==NULL)
            p->next[x]=new node();
        p=p->next[x];
        p->num++;
    }
}
ll trie_query(node *p,ll cnt)
{
    ll l,r,re=0;
    if(p->next[0]==NULL)l=0;
    else
    {
        l=p->next[0]->num;
        re=(re+trie_query(p->next[0],cnt+1))%mod;//计算出左子树
    }
    if(p->next[1]==NULL)r=0;
    else
    {
        r=p->next[1]->num;
        re=(re+trie_query(p->next[1],cnt+1))%mod;//计算出右子树
    }
    re+=l*r*(1<<cnt)%mod;
    return re;
}
int main()
{
    ll t,n,x,q=0;
    scanf("%lld",&t);
    while(t--)
    {
        scanf("%lld",&n);
        root=new node();
        for(ll i=0;i<n;i++)
        {
            scanf("%lld",&x);
            trie_add(x);
        }
        printf("Case #%lld: %lld\n",++q,trie_query(root,0)*2%mod);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值