题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5269
ZYB loves Xor I
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 1149 Accepted Submission(s): 510
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
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,5∗104] , Ai∈[0,229]
The first line has an integer n
The second line has n integers A1 , A2 .... An
n∈[1,5∗104] , 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
Source
Recommend
解析:建一个字典树,两个标记位0 1,分别存到当前0 1的个数,创建完成后,再遍历所有的数字,求下ans即可
代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 50009;
typedef long long LL;
const LL mod = 998244353ll;
int a[N];
LL ans;
typedef struct node
{
int cnt[2];
struct node *nx[3];
node()
{
memset(cnt, 0, sizeof(cnt));
memset(nx, 0, sizeof(nx));
}
}Q, *T;
void Creat(int n, T &root)
{
T q = root;
int k = 0;
while(true)
{
int id = n % 2;
if(q->nx[id] == NULL)
q->nx[id] = new node();
q->cnt[id]++;
q = q->nx[id];
k++;
if(k == 30) break;
n /= 2;
}
}
void Find(int n, T &root, int len)
{
T q = root;
int bits[33];
for(int i = 0; i <= 30; i++)
{
bits[i] = n % 2;
n /= 2;
}
int k = 1, num = 0;
for(int i = 0; i <= 30; i++)
{
int id = bits[i];
num += q->cnt[!id];
ans += k*q->cnt[!id];
ans %= mod;
q = q->nx[id];
if(num >= len-1) break;
k *= 2;
}
}
void F(T S)
{
if(S == NULL) return ;
for(int i = 0; i < 2; i++)
{
if(S->nx[i]) F(S->nx[i]);
}
delete S;
S = NULL;
}
int main()
{
int t, n, cnt = 0;
scanf("%d", &t);
while(t--)
{
T root = new node();
scanf("%d", &n);
for(int i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
Creat(a[i], root);
}
ans = 0;
for(int i = 1; i <= n; i++)
{
Find(a[i], root, n);
}
printf("Case #%d: %lld\n", ++cnt, ans);
F(root);
}
return 0;
}