K - Birthday Puzzle (巧妙的dfs)

ZZ --瑞 hopeACMer参考了这位大佬的代码,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\le n \le 20),n(1≤n≤20), the size for array aa The second line contains nn integers, a_{i}(1 \le a_{i} \le 10^5)ai​(1≤ai​≤105) the array aa elements

Output

Help the beautiful girl to find the answer for the puzzle.

Sample 1

InputcopyOutputcopy
3
1 2 3
18

题意:给你一个数组,让你找出它所有子集(任意删除零个或多个元素)的OR(按位或)之和。

乍一想真的是一点思路都妹有,然后想到了dfs,但是不知道怎么实现,参考了大佬的代码,真的是感叹dfs太叹为观止了。

话不多说先上代码:

#include <bits/stdc++.h>

using namespace std;
long long int ans=0;
int n;
int a[25];
void dfs(int p,int last)//p代表当前数组下标,last表示上一个数组中的值,用来做or运算
{
    if(p>n)
        return;
    int t;
    for(int i=p;i<=n;i++)
    {
        t=last|a[i];
        ans+=t;
        dfs(i+1,t);
    }
}
int main()
{
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
    }
    dfs(1,0);//数组下标从1开始,0和任何数or运算都是那个数
    printf("%lld\n",ans);
    return 0;
}

友友们看一下样例的递归过程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值