
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Triples with Bitwise AND Equal To Zero in C++
Suppose we have an array of integers A. We have to find the number of triples of indices (i, j, k) such that −
0 <= i < size of A
0 <= j < size of A
0 <= k < size of A
A[i] AND A[j] AND A[k] is 0, where AND represents the bitwise-AND operator.
So, if the input is like [3,1,2], then the output will be 12
To solve this, we will follow these steps −
Define one map m
ret := 0
n := size of A
for initialize i := 0, when i < n, update (increase i by 1), do −
for initialize j := 0, when j < n, update (increase j by 1), do −
for initialize j := 0, when j < n, update (increase j by 1), do −
for initialize i := 0, when i < n, update (increase i by 1), do −
x := A[i]
for all key-value pairs a in m
if (a.key AND x) is same as 0, then −
ret := ret + a.value
return ret
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: int countTriplets(vector<int>& A){ unordered_map<int, int> m; int ret = 0; int n = A.size(); for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { m[A[i] & A[j]]++; } } for (int i = 0; i < n; i++) { int x = A[i]; for (auto& a : m) { if ((a.first & x) == 0) { ret += a.second; } } } return ret; } }; main(){ Solution ob; vector<int> v = {3,1,2}; cout << (ob.countTriplets(v)); }
Input
{3,1,2}
Output
12
- Related Articles
- Maximum subset with bitwise OR equal to k in C++
- Largest set with bitwise OR equal to n in C++
- What are the bitwise zero fill right shift zero operators in Java?
- Find subsequences with maximum Bitwise AND and Bitwise OR in Python
- Construct Quadruples, Triples, and Indirect Triples for the expression\n-(a + b) * (c + d) - (a + b + c)
- Maximum steps to transform 0 to X with bitwise AND in C++
- Find N distinct numbers whose bitwise Or is equal to K in Python
- Find N distinct numbers whose bitwise Or is equal to K in C++
- Program to make the XOR of all segments equal to zero in Python
- Count pairs with Bitwise AND as ODD number in C++
- Count pairs with Bitwise-AND as even number in C++
- Performing Bitwise Operations with BigInteger in Java
- Bitwise AND and OR in Arduino
- Count zero, NULL and distinct values except zero and NULL with a single MySQL query
- What is Bitwise AND in C++?
