And Closure
Time limit:
1000 ms
Memory limit: 128 MB
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^51≤N≤105
- 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.
Input | Output |
---|---|
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;
}