您的位置:首页 > 编程语言 > C语言/C++

[C++]bitset特殊用法

2016-05-20 17:25 344 查看

bitset特殊用法

本文我们介绍一个用bitset来解决特殊的问题。

问题产生

Give you N numbers a[1]…a

and M numbers b[1]…b[m]

For each b[k], if we can find i,j a[i] + a[j] = b[k] or a[i] = b[k] , we say k is a good number.

And you should only output the number of good numbers.

0 < n, m, a[i], b[j] <= 200000

sample input

3 6
1
3
5
2
4
5
7
8
9

sample output

4

b[1]…b[m] 2,4,5,7,8,9

2 = 1+1

4 = 1+3

5 = 5

8 = 3+5

问题分析

这题乍看起来是比较简单的,可能最开始会尝试用枚举所有的情况,但这样的复杂度是O(n*m),必然会超时,特别是对于十万级数据时,所以我们必须尝试使用一种更为快捷的方式。

这里我们使用bitset来完成问题。把a中所有的值都作为position定为在bitset里面,然后对这个bitset进行移位操作,最后就可以快速地得到所有可能的情况。

算法思路

利用bitset的非标准做法。利用bitset记录哪些数在a中出现过了。那么把这个bitset左移1位,我们就可以得到有哪些x(x=a[i]+1)出现过了。左移两位,就知道哪些x(x = a[i]+2)出现过。如果此处左移a[1]那么,得到的就是a[1]+a[1] ,… ,a[1]+a
这些数字的bitset。枚举a[1]到a
来左移,把结果取或,就能得到a[i]+a[j]的集合,再或上a[1]..a
的bitset,把这个结果和b[1]..b[m]的bitset取&, 剩下的这个bitset有多少个1,答案就是几。

问题解决

#include <iostream>
#include <bitset>
#include <vector>
#define MAX_ELE 200000
using namespace std;
int main() {
int n, m;
cin >> n >> m;
bitset<MAX_ELE> a;
bitset<MAX_ELE> b;
int pos;
vector<int> temp;
temp.reserve(MAX_ELE);
while (n--) {
cin >> pos;
temp.push_back(pos);
a.set(pos);
}
while (m--) {
cin >> pos;
b.set(pos);
}
bitset<MAX_ELE> T_a = a;
for (int i = 0; i != temp.size(); i++) {
a = a | (T_a << temp[i]);
}
b = b & a;
cout << b.count() << endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: