K - Birthday Puzzle ( DFS遍历数组 )
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 aa, the answer is obtained by doing OR operation to the numbers in each subset of array aa, 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),n(1≤n≤20), the size for array aa The second line contains nn integers, ai(1≤ai≤105)ai(1≤ai≤105) the array aa 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 aa is another array that can be obtained by removing zero or more elements from aa.
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
题意: 说现在有一个数组,有一种OR操作 或(|) 。 输出所有可能的情况累加的结果。例如 1 2 3 可以有 1 , 2 , 3 , 1|2 , 1|3 , 2|3 , 1|2|3 。
思路: 就是遍历所有的情况。用dfs,比如这里有数组 1 2 3 4 5 6 7 8 9 , 从DFS(int node,int presum),意思是第node个点,之前的值为presum.
当BFS到5的时候, DFS(5,16), 那么在dfs里面需要调用两次dfs一次是,之前的值和node5做了运算,即DFS(5+1,16|a[5]); 一次是,之前的值没和node5做运算,即DFS(5+1,16)。
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int a[22];
int n;
ll ans = 0;
void bfs( int node, int presum ) // 当前点,之前点的值
{
if ( node==n+1 ) {
return ;
}
ll temp = presum|a[node];
ans += temp;
bfs(node+1,temp); // 当前点参与运算
bfs(node+1,presum); // 当前点没有参加运算
}
int main()
{
int i;
cin >> n;
for ( i=1; i<=n; i++ ) {
cin >> a[i];
}
bfs(1,0);
cout << ans << endl;
return 0;
}