-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
count-triplets-with-even-xor-set-bits-i.cpp
71 lines (65 loc) · 2.37 KB
/
count-triplets-with-even-xor-set-bits-i.cpp
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
66
67
68
69
70
71
// Time: O(nlogr), r = max(max(a), max(b), max(c))
// Space: O(1)
// bit manipulation, parity
class Solution {
public:
int tripletCount(vector<int>& a, vector<int>& b, vector<int>& c) {
const auto& count = [](const auto& a) {
const auto& odd = accumulate(cbegin(a), cend(a), 0, [](const auto& total, const auto& x) {
return total + (__builtin_popcount(x) & 1);
});
return vector<int>{static_cast<int>(size(a)) - odd, odd};
};
vector<vector<int>> cnt = {count(a), count(b), count(c)};
int result = 0;
for (int i = 0; i < 4; ++i) {
result += cnt[0][i == 0 || i == 1 ? 0 : 1] *
cnt[1][i == 0 || i == 2 ? 0 : 1] *
cnt[2][i == 0 || i == 3 ? 0 : 1];
}
return result;
}
};
// Time: O(nlogr), r = max(max(a), max(b), max(c))
// Space: O(1)
// bit manipulation, parity
class Solution2 {
public:
int tripletCount(vector<int>& a, vector<int>& b, vector<int>& c) {
const auto& count = [](const auto& a) {
const auto& odd = accumulate(cbegin(a), cend(a), 0, [](const auto& total, const auto& x) {
return total + (__builtin_popcount(x) & 1);
});
return pair(static_cast<int>(size(a)) - odd, odd);
};
const auto& [even1, odd1] = count(a);
const auto& [even2, odd2] = count(b);
const auto& [even3, odd3] = count(c);
return even1 * even2 * even3 + even1 * odd2 * odd3 + odd1 * even2 * odd3 + odd1 * odd2 * even3;
}
};
// Time: O(n^3 * logr), r = max(max(a), max(b), max(c))
// Space: O(1)
// brute force, bit manipulation
class Solution3 {
public:
int tripletCount(vector<int>& a, vector<int>& b, vector<int>& c) {
const auto& count = [](const auto& a) {
const auto& odd = accumulate(cbegin(a), cend(a), 0, [](const auto& total, const auto& x) {
return total + (__builtin_popcount(x) & 1);
});
return pair(static_cast<int>(size(a)) - odd, odd);
};
int result = 0;
for (const auto& x : a) {
for (const auto& y : b) {
for (const auto& z : c) {
if (__builtin_popcount(x ^ y ^ z) % 2 == 0) {
++result;
}
}
}
}
return result;
}
};