B. Rock and Lever(位运算+思维)Codeforces Round #672 (Div. 2)
原题链接: https://codeforces.com/contest/1420/problems
测试样例
input
5
5
1 4 3 7 10
3
1 1 1
4
6 2 5 3
2
2 4
1
1
output
1
3
2
0
0
Note
In the first test case there is only one pair: (4,7): for it 4 & 7=4, and 4⊕7=3.
In the second test case all pairs are good.
In the third test case there are two pairs: (6,5) and (2,3).
In the fourth test case there are no good pairs.
题意: 给你一个数组,求出 i < j i<j i<j时, a i & a j ≥ a i ⊕ a j a_i\&a_j \ge a_i \oplus a_j ai&aj≥ai⊕aj成立情况的总数。
解题思路: 一道出的很好的位运算的题。我们先来认识一下位运算:
0
&
0
=
=
0
=
0
=
=
0
⊕
0
0\&0==0\space\space=\space\space\space0==0\oplus0
0&0==0 = 0==0⊕0
0
&
1
=
=
0
<
1
=
=
0
⊕
1
0\&1==0\space\space<\space\space\space1==0\oplus1
0&1==0 < 1==0⊕1
1
&
0
=
=
0
<
1
=
=
1
⊕
0
1\&0==0\space\space<\space\space\space1==1\oplus0
1&0==0 < 1==1⊕0
1
&
1
=
=
1
>
0
=
=
1
⊕
1
1\&1==1\space\space>\space\space\space0==1\oplus1
1&1==1 > 0==1⊕1
我们发现了什么,除了第一种和最后一种满足,其他都是小于按位异或操作的。
我们再来看一个例子:
a
=
101001
a=101001
a=101001
b
=
110000
b=110000
b=110000
那么
a
&
b
=
100000
a
⊕
b
=
011001
a\& b=100000\space\space a\oplus b=011001
a&b=100000 a⊕b=011001,这样我们发现了什么?如果最高位相同的话,那么进行与操作可以还是为1,进行异或操作就变为0了,而判断两个数的大小比较的就是最高位,所以我们在进行过程中只要判断最高位就行(最高位当然是说的1的最高位)。所以这道题只需要记录最高位的出现次数,用后面的加上前面最高位相同的数量,即是本题的所有情况总数。(仔细理解)具体看代码。
AC代码
/*
*邮箱:unique_powerhouse@qq.com
*blog:https://me.csdn.net/hzf0701
*注:文章若有任何问题请私信我或评论区留言,谢谢支持。
*
*/
#include<bits/stdc++.h> //POJ不支持
#define rep(i,a,n) for (int i=a;i<=n;i++)//i为循环变量,a为初始值,n为界限值,递增
#define per(i,a,n) for (int i=a;i>=n;i--)//i为循环变量, a为初始值,n为界限值,递减。
#define pb push_back
#define IOS ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
#define fi first
#define se second
#define mp make_pair
using namespace std;
const int inf = 0x3f3f3f3f;//无穷大
const int maxn = 1e5+7;//最大值。
typedef long long ll;
typedef long double ld;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
//*******************************分割线,以上为自定义代码模板***************************************//
ll t,n;
ll cnt[50];//记录最高位的数字数量。
ll a[maxn];
int main(){
//freopen("in.txt", "r", stdin);//提交的时候要注释掉
IOS;
while(cin>>t){
while(t--){
cin>>n;
rep(i,0,n-1){
cin>>a[i];
}
memset(cnt,0,sizeof(cnt));//初始化
//遍历统计。
ll ans=0;
rep(i,0,n-1){
ll start=1,pos=0;//start表示初始位置,pos记录最高位应该存储的下标。
while(start*2<=a[i]){
start<<=1;//值升高一位。
pos++;//位置升高一位
}
ans+=cnt[pos];//加上最高位相同的之前下标的数量。
cnt[pos]++;//又发现一个,数量+1.
}
cout<<ans<<endl;
}
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!