计算元素对,使其 OR 中的设置位数为 B[i]
给定两个数组A[]和B[] ,每个数组有N个元素。任务是找到索引对(i, j)的数量,使得i ≤ j和F(A[i] | A[j]) = B[j]其中F(X)是设置位的计数X的二进制表示。
例子
Input: A[] = {5, 3, 2, 4, 6, 1}, B[] = {2, 2, 1, 4, 2, 3}
Output: 7
All possible pairs are (5, 5), (3, 3), (2, 2),
(2, 6), (4, 6), (6, 6) and (6, 1).
Input: A[] = {4, 3, 5, 6, 7}, B[] = {1, 3, 2, 4, 5}
Output: 4
方法:遍历所有可能的对 (i, j) 并检查其 OR 值中设置位的计数。如果计数等于 B[j],则增加计数。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to return the count of pairs
// which satisfy the given condition
int solve(int A[], int B[], int n)
{
int cnt = 0;
for (int i = 0; i < n; i++)
for (int j = i; j < n; j++)
// Check if the count of set bits
// in the OR value is B[j]
if (__builtin_popcount(A[i] | A[j]) == B[j]) {
cnt++;
}
return cnt;
}
// Driver code
int main()
{
int A[] = { 5, 3, 2, 4, 6, 1 };
int B[] = { 2, 2, 1, 4, 2, 3 };
int size = sizeof(A) / sizeof(A[0]);
cout << solve(A, B, size);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to return the count of pairs
// which satisfy the given condition
static int solve(int A[], int B[], int n)
{
int cnt = 0;
for (int i = 0; i < n; i++)
for (int j = i; j < n; j++)
// Check if the count of set bits
// in the OR value is B[j]
if (Integer.bitCount(A[i] | A[j]) == B[j])
{
cnt++;
}
return cnt;
}
// Driver code
public static void main(String args[])
{
int A[] = { 5, 3, 2, 4, 6, 1 };
int B[] = { 2, 2, 1, 4, 2, 3 };
int size = A.length;
System.out.println(solve(A, B, size));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 implementation of the approach
# Function to return the count of pairs
# which satisfy the given condition
def solve(A, B, n) :
cnt = 0;
for i in range(n) :
for j in range(i, n) :
# Check if the count of set bits
# in the OR value is B[j]
if (bin(A[i] | A[j]).count('1') == B[j]) :
cnt += 1;
return cnt
# Driver code
if __name__ == "__main__" :
A = [ 5, 3, 2, 4, 6, 1 ];
B = [ 2, 2, 1, 4, 2, 3 ];
size = len(A);
print(solve(A, B, size));
# This code is contributed by AnkitRai01
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to return the count of pairs
// which satisfy the given condition
static int solve(int []A, int []B, int n)
{
int cnt = 0;
for (int i = 0; i < n; i++)
for (int j = i; j < n; j++)
// Check if the count of set bits
// in the OR value is B[j]
if (bitCount(A[i] | A[j]) == B[j])
{
cnt++;
}
return cnt;
}
static int bitCount(long x)
{
// To store the count
// of set bits
int setBits = 0;
while (x != 0)
{
x = x & (x - 1);
setBits++;
}
return setBits;
}
// Driver code
public static void Main(String []args)
{
int []A = { 5, 3, 2, 4, 6, 1 };
int []B = { 2, 2, 1, 4, 2, 3 };
int size = A.Length;
Console.WriteLine(solve(A, B, size));
}
}
/* This code is contributed by PrinciRaj1992 */
Javascript
输出:
7
时间复杂度: O(N 2 )
辅助空间: O(1)