Repository navigation
Expand file tree
/
Copy pathaiacubiti.cpp
More file actions
66 lines (52 loc) · 2.21 KB
/
Copy pathaiacubiti.cpp
File metadata and controls
66 lines (52 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
problem description :
given an array A of N integers. Find how many pairs of indices (i ,j) such that i <= j and the number
of different bits in A[i] and A[j] binary representations is exactly equal to 4. (1 <= N <= 10^5 ,0 <= A[i] < 2^20)
sample case :
N = 4 ,A = {15 ,0 ,10 ,5}
pairs that differ by exactly 4 bits are (1 ,2) and (3 ,4) ,so answer = 2.
a naive solution would be for each element flip every possible 4 bits and check if there exists an element
with that value this solution works in N*(20C4) which is not fast enough to pass.
lets create a dp[d][m] that stores the number of elements from the array that we can modify their value by flipping exactly d bits to be equal to m.
instead of flipping 4 bits for each element we can divide a number c into 2 halves a = (n>>10) and b = n&((1<<10)-1) so that c = (a*2^10)+b
now flip at most 4 bits in a and increase dp[d][m_a*2^10+b] by 1 where m_a is the modified a and d is # of diff bits between a and m_a
then for the second half flip at most 4 bits and add to the answer dp[4-d][a*2^10+m_b] where m_b is modified b and d is # of diff bits between b and m_b
this will be equivalent to flipping all 4 bits for each element.
time complexity : O(N*2^10)
because of tight tl we will have to do loop unrolling manually or by using pragma.
since the 2 inner loops are really simple they can be unrolled and would save processing time.
*/
#pragma GCC optimize ("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
#define MAX_N 100005
int n;
int a[MAX_N];
int dp[5][1024*1024];
int main()
{
freopen("aiacubiti.in" ,"r" ,stdin);
freopen("aiacubiti.out" ,"w" ,stdout);
int popcount[1024];
for(int b=0; b<1024; b++)
popcount[b] = __builtin_popcount(b);
scanf("%d",&n);
for(int i=0; i<n; i++)
scanf("%d",&a[i]);
long long ans = 0;
for(int i=0; i<n; i++)
{
int fh = (a[i]>>10) ,sh = (a[i]&1023);
for(int d ,b=0; b<1024; b++){
d = popcount[b^sh];
if(d <= 4)
ans += dp[4-d][(fh<<10)|b];
}
for(int d ,b=0; b<1024; b++){
d = popcount[b^fh];
if(d <= 4)
dp[d][(b<<10)|sh]++;
}
}
printf("%lld\n",ans);
}