And Closure(动态规划)

And Closure

Time limit:  1000 ms
Memory limit:  128 MB

You are given an array of NN integers. You can choose any subset of numbers and compute their binary and (operator \&& in some languages). Find the number of distinct results you can get.

Standard input

The first line contains a single integer NN.

The second line contains the NN elements of the array.

Standard output

Output a single number representing the number of different results you can get.

Constraints and notes

  • 1 \leq N \leq 10^51N105
  • The elements of the array are integers between 00 and 10^6106.
  • The chosen subset can be empty, and in this case we consider the and of the elements to be 00.
InputOutput
4
1 3 6 7
6
4
23 54 39 23
8

题意:给你一个序列,问子集的与的和最多能得到多少个不同的数。

首先,空集是属于子集的一种的,故0肯定是存在的。

对于与运算,我们首先要知道,a&b<=min(a,b),即说明了对于某一个值c,若c是由其他两个数a跟b相与得到,则

a跟b的二进制的1的位肯定是包含了c的,现在我们考虑这样的转移:每一个数a都认为是比他二进制数多一个1的数

与其他数相与得来的,然后将能得到这个数的这些数与起来,若刚好得到这个数a,则说明这个数是可以通过已给的

数得来的,也就是说,存在一个子集的与得到这个数!

感觉说的有一点迷糊,看代码可能会清楚一点。


代码如下:

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <cmath>
#include <cstring>
#include <utility>
#include <list>
#include <vector>
#include <cstdlib>
#include <bitset>
#define rep(i,a,b) for(int i=a;i<=b;i++)
#define repn(i,n) for(int i=n;i>=1;i--)
#define mst(a,x) memset(a,x,sizeof(a))
#define ll long long
using namespace std;
const int maxn = 100000;
const int maxm = 1000000;
const double pi = 3.141592653589793;
const double e = 2.718281828459045;
int dp[maxm + 50];
int main()
{
#ifdef local
    freopen("in.txt","r",stdin);
#endif // local
    int n;
    cin >> n;
    mst(dp,-1);  //将dp初始为-1,  (-1 的二进制为全1)
    rep(i,1,n)
    {
        int t;
        cin >> t;
        dp[t] = t;  
    }

    dp[0] = 0; // 空集

    for (int i = 1e6; i >= 0; i--) //注意是从大到小枚举
    {
        for (int j = 0; j < 20; j++) //枚举二进制位
            if ((1<<j) & i)
            {
                dp[i-(1<<j)] &= dp[i]; // 将得到当前值 (i-(1<<j))(除去一个1) 的所有数相与
            }
    }

    int ret = 0;

    for (int i = 0; i <= 1e6; i++) ret += (dp[i]==i); //计算所有可能得到的值

    cout << ret << '\n';

    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值