bitset简单用法

bitset的创建:

#include<bitset>

bitset<32> ar; //默认全为0
bitset<32> ar(n); //n的二进制
bitset<32> ar(str); //01串
bitset<n> ar(str,pos,n); //从str第p位开始的n位

###基础用法:
ar.size();//返回位数
ar.count();//返回1的个数
ar.any();//返回是否有1
ar.none();//返回是否没有1
ar.test(p);//返回第p位是不是1
ar.set();//全部设为1
ar.set(p);//第p位设为1
ar.reset();//全部设为0
ar.reset(p);//第p位设为0
ar.flip();//全部反转
ar.flip(p);//第p位反转
ar.to_ulong();//返回unsigned long
ar.to_ullong();//返回unsigned long long
ar.to_string();//返回string

###例题:
515. 「LibreOJ β Round #2」贪心只能过样例

(牛客练习赛22也有这个题)

AC代码:

#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <bitset>
#define lowbit(x) (x&(-x))
using namespace std;
typedef long long LL;
const int N = 1e6 + 7;
const int INF = 0x3f3f3f3f;
int n, l, r;
int main(int argc, char const *argv[]){
  while(~scanf("%d", &n)){
    bitset<1000005> a, b;
    b[0] = 1;
    while(n--){
      scanf("%d%d", &l, &r);
      for(int i = l; i <= r; ++i){
        a |= (b<<i*i);
      }
      b = a;
      a.reset();
    }
    printf("%d
", b.count());
  }
  return 0;
}

####统计二进制中1的数量:
//方法一:
int bitCount(unsigned int n){
    unsigned int tmp = n - ((n >> 1) & 033333333333) - ((n >> 2) & 011111111111);
    return ((tmp + (tmp >> 3)) & 030707070707) % 63;
}

//方法二:
bitset<32> a(n);
a.count();

//方法三:
__builtin_popcount(n)//返回二进制位中有多少个1
__builtin_popcountll//longlong
__builtin_parity(n)//返回二进制位中1的数量的奇偶性,奇数返回1,偶数返回0
__builtin_ffs(n)//返回二进制末尾最后一个1的位置,从一开始
__builtin_ctz(n)//返回二进制末尾后面0的个数,当n为0时,和n的类型有关

#define LeftPos(x) 32 - __builtin_clz(x) - 1
#define LeftPosll(x) 64 - __builtin_clzll(x) - 1
原文地址:https://www.cnblogs.com/Cwolf9/p/9513241.html