[C++]bitset特殊用法

bitset特殊用法

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

问题产生

Give you N numbers a[1]…a[n]
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[n]这些数字的bitset。枚举a[1]到a[n]来左移,把结果取或,就能得到a[i]+a[j]的集合,再或上a[1]..a[n]的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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值