K - Birthday Puzzle Gym - 102267K (遍历子集的位运算)

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

给你一个集合,让你求子集的异或和。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;
 }
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
#define PI 3.14159265358



int main()
{
    int n;
    cin>>n;
    int a[22];
    int b[22];
    int i,j,k;
    long long int res = 0;
    for(i=0; i<n; i++)
    {
        scanf("%d",&a[i]);
    }
    for (int i = 1; i < (1 << n); i++)
    {
        int len = 0;
        for (int j = 0; j < n; j++)
            if (i & (1 << j))
            {
                b[len++] = a[j];
            }
        int ans = 0;
        for(int j=0; j<len; j++)
        {
            ans = ans|b[j];
        }
        res +=ans;
    }
    cout<<res<<endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值