hdu 5269 ZYB loves Xor I(字典树)

来源:互联网 发布:本机mac地址怎么查 编辑:程序博客网 时间:2024/05/18 03:56

ZYB loves Xor I

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1142    Accepted Submission(s): 506


Problem Description
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(Ai xor Aj)) (i,j[1,n])
We define that lowbit(x)=2k,k is the smallest integer satisfied ((x and 2k)>0)
Specially,lowbit(0)=0
Because the ans may be too big.You just need to output ans 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 n
The second line has n integers A1,A2....An
n[1,5104]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
254 0 2 7 052 6 5 4 0
 

Sample Output
Case #1: 36Case #2: 40
 

题意:给出一列数,求任意两个数的异或值得lowbit值和

解:一个数的lowbit为,第一个不为0的数前有k个0,则为2^k,所以直接在建树的时候计算不同的位的数的数量,相乘即可

#include<iostream>#include<algorithm>#include<cstdio>#include<cstdlib>#include<cstring>#include<vector>#include<map>#include <bits/stdc++.h>using namespace std;const int N = 1e5+10;typedef long long LL;const LL mod = 998244353;int rt[N*30][3], sum[N*30], cnt;LL bit[35];LL ans;void init(){    rt[0][0]=rt[0][1]=-1;    memset(sum,0,sizeof(sum));    cnt=1, ans=0;    return ;}void add(LL x){    int root=0;    for(int i=0;i<=30;i++)    {        int v=(x&(1<<i))?1:0;        if(rt[root][v]==-1)        {            rt[root][v]=cnt;            rt[cnt][0]=rt[cnt][1]=-1;            sum[cnt]=0;            cnt++;        }        if(rt[root][1^v]!=-1)        {            ans=(ans+(LL)bit[i]*sum[rt[root][1^v]]%mod)%mod;        }        root=rt[root][v];        sum[root]+=1;    }    return ;}int main(){    int t, ncase=1, n;    scanf("%d", &t);    bit[0]=1;    for(int i=1;i<=30;i++) bit[i]=bit[i-1]*2;    while(t--)    {        scanf("%d", &n);        init();        for(int i=0;i<n;i++)        {            LL x;            scanf("%lld", &x);            add(x);        }        ans=(ans*2)%mod;        printf("Case #%d: %lld\n",ncase++,ans);    }    return 0;}









原创粉丝点击