位运算
知识点:
自然溢出
- 自带一个取模 相当于 相当于
溢出(超过位数):不知道 未定义行为
获取 变成二进制之中 的数量
短除法:时间复杂度为 库函数(接近 )
获取 的二进制最低位 所截取的二进制数
基础的位运算操作
前置知识:
- 获取二进制的第 位
- 让 的第 位变成
- ~
- 让 的第 位变成
- 取反
课堂练习
-T739864 位运算基础试题1-
思路
- 题目要求一个数二进制下的最低位的 ,直接用上面说的 函数即可(最简)
- 其实也可以枚举, 从后往前枚举找到第一个 即可
Code:
#include<bits/stdc++.h>
#define int long long
using namespace std;
int x;
int lowbit(int x)
{
return x&(-x);
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin>>x;
cout<<lowbit(x);
return 0;
}-T739863 位运算基础试题2-
思路
- 没啥好讲的,三个操作分别套用上面三个公式即可
Code:
#include<bits/stdc++.h>
#define int long long
using namespace std;
int x,T,op,pos;
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin>>x>>T;
while(T--)
{
cin>>op>>pos;
int tmp=(x>>pos) & 1;//获取x的第pos位
if(op==1)
{
if(tmp==1) x &= (~(1ll<<pos));
}
else if(op==2)
{
if(tmp==0) x |= (1ll<<pos);
}
else if(op==3)
{
x ^= (1ll<<pos);
}
cout<<x<<"\n";
}
return 0;
}-B3919 [语言月赛 202401] 二进制与一-
思路
- 循环 判断当前位是否为 ,是则跳过,否则计算最小 ,即 ,并且将 累加到答案,最后输出 的总和即可
Code:
#include<bits/stdc++.h>
#define int long long
using namespace std;
int n,q,pos,ans=0;
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin>>n>>q;
while(q--)
{
cin>>pos;
if(((n>>(pos-1))&1)==1) continue;
int x=(1ll<<(pos-1))-n%(1ll<<pos);
n+=x;
ans+=x;
}
cout<<ans;
return 0;
}-P9451 [ZSHOI-R1] 新概念报数-
思路
- 循环用 计算 的二进制中 的个数,若个数 (非法),则输出 ,否则找下一个合法数
- 找合法数
- 若 的个数为 (如 ),则下一个合法数是
- 若 的个数为 (如 ),下一个合法数是
Code:
#include<bits/stdc++.h>
#define int long long
#define pop __builtin_popcountll
using namespace std;
int T,x;
int lowbit(int x)
{
return (x&(-x));
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin>>T;
while(T--)
{
cin>>x;
if(pop(x)>=3) cout<<"No,Commander";
else if(pop(x)==1) cout<<x+1;
else cout<<x+lowbit(x);
cout<<"\n";
}
return 0;
}-T739897 位运算进阶1-
思路
- 异或性质:一个数异或自身偶数次抵消(结果为 ),奇数次不变(结果为自身)
- 贡献次数计算:对查询区间 ,元素 出现在 个子区间中(即该数在总异或和中出现的次数)
- 以 为右端点的左端点选择数~
- 以 为左端点的右端点选择数~
贡献判断
- 次数为奇数
- 偶数 无贡献
操作处理
- 直接修改 为
- 遍历 计算每个元素的贡献次数奇偶性,累加异或结果 最后在每个 循环结束后输出总异或结果即可
Code:
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int N=1e7+10;
int n,q,a[N],op,x,y;
signed main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin>>n>>q;
for(int i=1;i<=n;i++) cin>>a[i];
while(q--)
{
cin>>op>>x>>y;
if(op==1) a[x]=y;
else
{
int ans=0;
for(int i=x;i<=y;i++)
{
int tmp=(i-x+1)*(y-i+1);
if(tmp%2==1) ans^=a[i];
}
cout<<ans<<"\n";
}
}
return 0;
}