I - Birthday Puzzle
Today is the Birthday of a beautiful girl, she’s happy and she’s telling her friends loudly to bring her birthday gifts. One of her best friends who is fond of puzzles decided to bring her a very special gift, a magic box, this box cannot be opened unless the beautiful girl solves the mysterious puzzle written on the box and writes the answer on a small piece of paper under where the puzzle is written.
“You are given an array a, the answer is obtained by doing OR operation to the numbers in each subset of array a, then by summing all the subset ORing results”. Help the beautiful girl to find the answer so she can open the magic box and continue celebrating her blessed birthday.
Input
The first line contains integer n(1≤n≤20), the size for array a The second line contains n integers, ai(1≤ai≤105) the array a elements
Output
Help the beautiful girl to find the answer for the puzzle.
Example
Input
3
1 2 3
Output
18
Note
Note: a subset of an array a is another array that can be obtained by removing zero or more elements from a.
The first sample subsets:
1
2
3
1|2 = 3
1|3 = 3
2|3 = 3
1|2|3 = 3
Answer = 1+2+3+3+3+3+3 = 18
Where | is the OR operation.
For more information about the OR operation use this link: https://en.wikipedia.org/wiki/Bitwise_operation#OR
题目大意:
给你一个集合,让你求子集的异或和。N<=20.
数据不大,但这里涉及遍历子集的操作。
for (int i=0;i<(1<<n);i++){
for (int j=0;j<n;j++)
if (i&(1<<j)) cout<<a[j]<<" ";
cout<<endl;
}
这行代码即可将子集输出。
首先,i<(1<<n)的1<<n即
2
n
2^n
2n,即非空子集的个数是
2
n
−
1
2^n-1
2n−1。
然后有点类似状态压缩的方法。i的作用就是n个取几个(二进制0代表不取,1代表取)
∑
\displaystyle\sum
∑
C
n
1
+
C
n
2
+
C
n
3
+
.
.
.
+
C
n
n
C^1_n+C^2_n+C^3_n+...+C^n_n
Cn1+Cn2+Cn3+...+Cnn的选取方法刚好是
2
n
2^n
2n-1的二进制0,1。
i&(1<<j) 就是判断当二进制为1的时候输出。即遍历了所有的子集。然后问题就解决啦。
#include<cstdio>
#include<iostream>
using namespace std;
long long a[25],cnt,num=0;
void solve(int n)
{
for (int i=0;i<(1<<n);i++){
cnt=0;
for (int j=0;j<n;j++)
if (i&(1<<j)) cnt=cnt|a[j];
num+=cnt;
}
}
int main()
{
int n;
scanf("%d",&n);
for (int i=0;i<n;i++) cin>>a[i];
solve(n);
printf("%lld\n",num);
return 0;
}