当前位置:网站首页>[51nod 2493] sum of binary distances [bit operation]

[51nod 2493] sum of binary distances [bit operation]

2022-06-13 09:35:00 Ayane.

 Insert picture description here
l i n k link link

analysis :

n 2 n^2 n2 Violence is more You can count two x o r xor xor See how many there are 1 1 1
Complexity O ( n 2 l o g n ) O(n^2logn) O(n2logn)

You can also take apart each number binary If this bit has c n t 1 cnt_1 cnt1 individual 1 1 1 c n t 0 cnt_0 cnt0 individual 0 0 0 In the end c n t 0 × c n t 1 cnt_0\times cnt_1 cnt0×cnt1 Different
Complexity O ( n l o g n ) O(nlogn) O(nlogn)

CODE:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#define reg register
using namespace std;
typedef long long ll;
const int N=1e4+5;
int n,a[N],ans,cnt0[N],cnt1[N];
void calc(int x)
{
    
	for(int i=0;i<=30;i++)
		((x>>i)&1)?cnt1[i]++:cnt0[i]++;
}
int main(){
    
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
    
		scanf("%d",&a[i]);
		calc(a[i]);
	}
	for(int i=0;i<=30;i++)
		ans+=cnt1[i]*cnt0[i];
	printf("%d",ans);
	return 0;
}
原网站

版权声明
本文为[Ayane.]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202270530323834.html