Hug the princess(思维,位运算)

编程入门 行业动态 更新时间:2024-10-19 06:18:28

Hug the princess(<a href=https://www.elefans.com/category/jswz/34/1770010.html style=思维,位运算)"/>

Hug the princess(思维,位运算)

Hug the princess

Time Limit: 3000/1000MS (Java/Others)     Memory Limit: 65535/65535KB (Java/Others)
Submit  Status

There is a sequence with nn elements. Assuming they are a1,a2,⋯,ana1,a2,⋯,an.

Please calculate the following expession.

∑1≤i<j≤n(ai∧aj)+(ai|aj)+(ai&aj)∑1≤i<j≤n(ai∧aj)+(ai|aj)+(ai&aj)

In the expression above, ^ | & is bit operation. If you don’t know bit operation, you can visit

to get some useful information.

Input

The first line contains a single integer nn, which is the size of the sequence.

The second line contains nn integers, the ithith integer aiai is the ithith element of the sequence.

1≤n≤100000,0≤ai≤1000000001≤n≤100000,0≤ai≤100000000

Output

Print the answer in one line.

Sample input and output

Sample InputSample Output
2
1 2
6

Hint

Because the answer is so large, please use long long instead of int. Correspondingly, please use %lld instead of %d to scanf and printf.

Large input. You may get Time Limit Exceeded if you use "cin" to get the input. So "scanf" is suggested.

Likewise, you are supposed to use "printf" instead of "cout".

题解:

让求这个表达式,我们可以把求出每一位的前缀和,然后再根据每一位找出前面是1,是0的当前位的个数;然后加上cnt * (1 << j)就好了

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAXN = 1e5 + 100;
int num[MAXN][35];
int a[35];
int p[MAXN];
typedef long long LL;
int main(){int n;while(~scanf("%d", &n)){int x;memset(num, 0, sizeof(num));for(int i = 1; i <= n; i++){scanf("%d", &x);for(int j = 0; j < 33; j++){num[i][j] = num[i - 1][j] + x % 2;x = x / 2;}}LL ans = 0;for(int i = 1; i <= n; i++){int temp = 0, pos = -1;for(int j = 0; j < 33; j++){a[j] = num[i][j] - num[i - 1][j];//    printf("%d ", a[j]);}//puts("");for(int j = 0; j < 33; j++){int cnt = 0;if(a[j]){cnt += (i - 1 - num[i - 1][j]);cnt += i - 1;cnt += num[i - 1][j];}else{cnt += num[i - 1][j];cnt += num[i - 1][j];}ans += (LL)cnt * (1 << j);}}printf("%lld\n", ans);}return 0;
}

 

 

转载于:.html

更多推荐

Hug the princess(思维,位运算)

本文发布于:2024-02-06 03:20:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1745720.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:思维   Hug   princess

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!