bitset用法

赋值

bitset<4>a1;//长度为4,默认以0填充
bitset<8>a2;//长度为8,将12以二进制保存,前面用0补充


string s = "100101";
bitset<10>a3(s);//长度为10,前面用0补充

//实验检测,char在普通环境不能直接赋值给bitset
//要开c++11,针不戳
char s2[] = "10101";
bitset<13>a4(s2);//长度为13,前面用0补充
//所以这玩意noip上不能用……

cout<<a1<<endl;//0000
cout<<a2<<endl;//00001100
cout<<a3<<endl;//0000100101
cout<<a4<<endl;//0000000010101

访问和修改

bitset<4>a1("1011");//这个赋值方法只能在c++11里用,noip八行

//可以用上面位运算时的方法
bitset<4>a1(string("1011"));

cout<<a1[0]<<endl;//1
cout<<a1[1]<<endl;//1
cout<<a1[2]<<endl;//0
cout<<a1[3]<<endl;//1
//注意!这两种赋值方式都是反序赋值的
//所以输出值为1101;
//可以直接输出a1来输出正序

//bitset支持单点修改
a1[0]=0;
cout<<a1[0]<<endl;//0
cout<<a1<<endl;//0101

函数

bitset<8>foo(string("10011011"));

cout<<foo.count()<<endl;//5  (count函数用来求bitset中1的位数,foo中共有5个1
cout<<foo.size()<<endl;//8  (size函数用来求bitset的大小,一共有8位

cout<<foo.test(0)<< endl;//true  (test函数用来查下标处的元素是0还是1,并返回false或true,此处foo[0]为1,返回true
cout<<foo.test(2)<<endl;//false  (同理,foo[2]为0,返回false

cout<<foo.any()<<endl;//true  (any函数检查bitset中是否有1
cout<<foo.none()<<endl;//false  (none函数检查bitset中是否没有1
cout<<foo.all()<<endl;//false  (all函数检查bitset中是全部为1

例题

简单瞎搞题

题目链接

题意

给你n个数组,从每个数组随机选一个数,然后求每个数的平方和有几种

思路

这个题用bitset做比较简单,可以定义两个bitset,a,b然后让其中一个b[0]=1,然后让b左移每个数的平方个位置,再让a,b求|和最后得到的b数组中1的个数就是种类数

这个图可以帮助大家理解

代码

#include <bits/stdc++.h>
#define int long long
#define endl '\n'
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
using namespace std;
bitset<1000010>a,b;
signed main()
{
	IOS
	int T=1;
	//cin>>T;
	while(T--)
	{
        b[0]=1;
        int k;
        cin>>k;
        while(k--)
        {
            a.reset();
            int l,r;
            cin>>l>>r;
            for(int i=l;i<=r;i++)
                a|=b<<i*i;
            b=a;
        }
        cout<<a.count();
	}
	return 0;
}

小红组比赛

题目链接

题意

这一题跟上一题差不多给你n个数组,从每个数组随机选一个数,然后求每个数和与target(题目给得一个数)最少相差最少

思路

跟上题一样也是先求bitset的数组,得到数组在从target向上向下模拟,看b数组是否为1,最先为1的必定与target最少相差最少

代码

#include <bits/stdc++.h>
#define int long long
#define endl '\n'
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
using namespace std;
bitset<550000>a,b;
signed main()
{
	IOS
	int T=1;
	//cin>>T;
	while(T--)
	{
        b[0]=1;
		int m,n,c,mi,t;
        cin>>m>>n;
        while(m--)
        {
            a.reset();
            for(int i=1;i<=n;i++)
            {
                cin>>c;
                a|=b<<c;
            }
            b=a;
        }
        cin>>t;
        for(int i=t,j=t;;i--,j++)
        {
            if(b[i]==1&&i>=0)
            {
                mi=t-i;break;
            }
            if(b[j]==1&&j<=5000)
            {
                mi=j-t;break;
            }
        }
        cout<<mi<<endl;
	}
	return 0;
}
  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值