📌  相关文章
📜  Array 中对的计数,使得对和 X 的 XOR 的按位 AND 为 0

📅  最后修改于: 2021-10-27 07:14:56             🧑  作者: Mango

给定一个由N 个正整数和一个正整数X组成的数组arr[] ,任务是找到对(i, j)的数量,使得i < j(arr[i]^arr[j] )&X0 .

例子:

朴素的方法:解决给定问题的简单方法是生成给定数组的所有可能对,并计算满足给定条件的那些对(i, j) ,即i < j(arr[i]^arr[j ])X0 ..检查对于所有的对后,打印得到的总计

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the number of pairs
// that satisfy the given criteria i.e.,
// i < j and (arr[i]^arr[j] )&X is 0
int countOfPairs(int arr[], int N, int X)
{
    // Stores the resultant count
    // of pairs
    int count = 0;
 
    // Iterate over the range [0, N)
    for (int i = 0; i < N - 1; i++) {
 
        // Iterate over the range
        for (int j = i + 1; j < N; j++) {
 
            // Check for the given
            // condition
            if (((arr[i] ^ arr[j]) & X) == 0)
                count++;
        }
    }
 
    // Return the resultant count
    return count;
}
 
// Driver Code
int main()
{
    int arr[] = { 3, 2, 5, 4, 6, 7 };
    int X = 6;
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << countOfPairs(arr, N, X);
 
    return 0;
}


Java
// Java program for the above approach
class GFG
{
 
// Function to find the number of pairs
// that satisfy the given criteria i.e.,
// i < j and (arr[i]^arr[j] )&X is 0
public static int countOfPairs(int arr[], int N, int X)
{
    // Stores the resultant count
    // of pairs
    int count = 0;
 
    // Iterate over the range [0, N)
    for (int i = 0; i < N - 1; i++) {
 
        // Iterate over the range
        for (int j = i + 1; j < N; j++) {
 
            // Check for the given
            // condition
            if (((arr[i] ^ arr[j]) & X) == 0)
                count++;
        }
    }
 
    // Return the resultant count
    return count;
}
 
// Driver Code
public static void main(String args[])
{
    int arr[] = { 3, 2, 5, 4, 6, 7 };
    int X = 6;
    int N = arr.length;
    System.out.println(countOfPairs(arr, N, X));
}
}
 
// This code is contributed by gfgking.


Python3
# Python3 program for the above approach
 
# Function to find the number of pairs
# that satisfy the given criteria i.e.,
# i < j and (arr[i]^arr[j] )&X is 0
def countOfPairs(arr, N, X):
     
    # Stores the resultant count
    # of pairs
    count = 0
 
    # Iterate over the range [0, N)
    for i in range(N - 1):
         
        # Iterate over the range
        for j in range(i + 1, N):
             
            # Check for the given
            # condition
            if (((arr[i] ^ arr[j]) & X) == 0):
                count += 1
 
    # Return the resultant count
    return count
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 3, 2, 5, 4, 6, 7 ]
    X = 6
    N = len(arr)
     
    print(countOfPairs(arr, N, X))
 
# This code is contributed by mohit kumar 29


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the number of pairs
// that satisfy the given criteria i.e.,
// i < j and (arr[i]^arr[j] )&X is 0
static int countOfPairs(int []arr, int N, int X)
{
     
    // Stores the resultant count
    // of pairs
    int count = 0;
 
    // Iterate over the range [0, N)
    for(int i = 0; i < N - 1; i++)
    {
         
        // Iterate over the range
        for(int j = i + 1; j < N; j++)
        {
             
            // Check for the given
            // condition
            if (((arr[i] ^ arr[j]) & X) == 0)
                count++;
        }
    }
 
    // Return the resultant count
    return count;
}
 
// Driver Code
public static void Main()
{
    int []arr = { 3, 2, 5, 4, 6, 7 };
    int X = 6;
    int N = arr.Length;
     
    Console.Write(countOfPairs(arr, N, X));
}
}
 
// This code is contributed by SURENDRA_GANGWAR


Javascript


C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the number of pairs
// that satisfy the given criteria i.e.,
// i < j and (arr[i]^arr[j] )&X is 0
int countOfPairs(int arr[], int N, int X)
{
    // Stores the resultant count
    // of pairs
    int count = 0;
 
    // Initializing the map M
    unordered_map M;
 
    // Populating the map
    for (int i = 0; i < N; i++) {
        M[(arr[i] & X)]++;
    }
 
    // Count number of pairs for every
    // element in map using mathematical
    // concept of combination
    for (auto m : M) {
        int p = m.second;
 
        // As nC2 = n*(n-1)/2
        count += p * (p - 1) / 2;
    }
 
    // Return the resultant count
    return count;
}
 
// Driver Code
int main()
{
    int arr[] = { 3, 2, 5, 4, 6, 7 };
    int X = 6;
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << countOfPairs(arr, N, X);
    return 0;
}


Java
// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find the number of pairs
// that satisfy the given criteria i.e.,
// i < j and (arr[i]^arr[j] )&X is 0
static int countOfPairs(int[] arr, int N, int X)
{
     
    // Stores the resultant count
    // of pairs
    int count = 0;
 
    // Initializing the map M
    HashMap M = new HashMap();
 
    // Populating the map
    for(int i = 0; i < N; i++)
    {
        if (M.containsKey(arr[i] & X))
            M.put((arr[i] & X),
             M.get(arr[i] & X) + 1);
        else
            M.put(arr[i] & X, 1);
    }
 
    // Count number of pairs for every
    // element in map using mathematical
    // concept of combination
    for(Integer entry : M.keySet())
    {
        int p = M.get(entry);
 
        // As nC2 = n*(n-1)/2
        count += p * (p - 1) / 2;
    }
 
    // Return the resultant count
    return count;
}
 
// Driver Code
public static void main(String[] args)
{
    int[] arr = { 3, 2, 5, 4, 6, 7 };
    int X = 6;
    int N = arr.length;
     
    System.out.print(countOfPairs(arr, N, X));
}
}
 
// This code is contributed by ukasp


Python3
# Python3 program for the above approach
 
# Function to find the number of pairs
# that satisfy the given criteria i.e.,
# i < j and (arr[i]^arr[j] )&X is 0
def countOfPairs(arr, N, X):
     
    # Stores the resultant count
    # of pairs
    count = 0
 
    # Initialize the dictionary M
    M = dict()
     
    # Populate the map
    for i in range(0, N):
        k = arr[i] & X
        if k in M:
            M[k] += 1
        else:
            M[k] = 1
             
    # Count number of pairs for every
    # element in map using mathematical
    # concept of combination
    for m in M.keys():
        p = M[m]
         
        # As nC2 = n*(n-1)/2
        count += p * (p - 1) // 2
         
    # Return the resultant count
    return count
 
# Driver Code
if __name__ == '__main__':
 
    arr = [ 3, 2, 5, 4, 6, 7 ]
    X = 6
    N = len(arr)
 
    print(countOfPairs(arr, N, X))
 
# This code is contributed by MuskanKalra1


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the number of pairs
// that satisfy the given criteria i.e.,
// i < j and (arr[i]^arr[j] )&X is 0
static int countOfPairs(int []arr, int N, int X)
{
   
    // Stores the resultant count
    // of pairs
    int count = 0;
 
    // Initializing the map M
    Dictionary M = new Dictionary();
 
    // Populating the map
    for (int i = 0; i < N; i++) {
        if(M.ContainsKey(arr[i] & X))
           M[(arr[i] & X)]++;
        else
           M.Add(arr[i] & X,1);
    }
 
    // Count number of pairs for every
    // element in map using mathematical
    // concept of combination
    foreach(KeyValuePair entry in M)
    {
         int p = entry.Value;
 
        // As nC2 = n*(n-1)/2
        count += p * (p - 1) / 2;
    }
 
    // Return the resultant count
    return count;
}
 
// Driver Code
public static void Main()
{
    int []arr = { 3, 2, 5, 4, 6, 7 };
    int X = 6;
    int N = arr.Length;
    Console.Write(countOfPairs(arr, N, X));
}
}
 
// This code is contributed by ipg2016107.


Javascript


输出:
3

时间复杂度: O(N 2 )  
辅助空间: O(1)

高效的方法:上述方法也可以通过观察给定的方程来优化。因此,要执行(A[i]^A[j]) & X == 0 ,然后在(A[i]^A[j])的答案中取消设置位 X 在其中设置位的位置它的二进制表示是必需的。

通过仔细观察XA[i]A[j]之间的关系,发现X&A[i] == X&A[j] 。因此,想法是找到具有值arr[i]&X的数组元素的频率,并且可以将具有相同值的任何两个数字组合为一对。请按照以下步骤解决问题:

  • 初始化一个无序映射,比如M来存储具有特定值arr[i]^X的数字的计数。
  • 使用变量i迭代范围[0, N]并增加无序映射Marr[i]&X的值的计数。
  • 将变量计数初始化为0以存储对的结果计数。
  • 使用变量m迭代映射M并将(m.second)*(m.second – 1)/2的值添加到变量count
  • 完成以上步骤后,打印count的值作为结果。

下面是上述方法的实现:

C++

// C++ program for the above approach
 
#include 
using namespace std;
 
// Function to find the number of pairs
// that satisfy the given criteria i.e.,
// i < j and (arr[i]^arr[j] )&X is 0
int countOfPairs(int arr[], int N, int X)
{
    // Stores the resultant count
    // of pairs
    int count = 0;
 
    // Initializing the map M
    unordered_map M;
 
    // Populating the map
    for (int i = 0; i < N; i++) {
        M[(arr[i] & X)]++;
    }
 
    // Count number of pairs for every
    // element in map using mathematical
    // concept of combination
    for (auto m : M) {
        int p = m.second;
 
        // As nC2 = n*(n-1)/2
        count += p * (p - 1) / 2;
    }
 
    // Return the resultant count
    return count;
}
 
// Driver Code
int main()
{
    int arr[] = { 3, 2, 5, 4, 6, 7 };
    int X = 6;
    int N = sizeof(arr) / sizeof(arr[0]);
    cout << countOfPairs(arr, N, X);
    return 0;
}

Java

// Java program for the above approach
import java.util.*;
 
class GFG{
 
// Function to find the number of pairs
// that satisfy the given criteria i.e.,
// i < j and (arr[i]^arr[j] )&X is 0
static int countOfPairs(int[] arr, int N, int X)
{
     
    // Stores the resultant count
    // of pairs
    int count = 0;
 
    // Initializing the map M
    HashMap M = new HashMap();
 
    // Populating the map
    for(int i = 0; i < N; i++)
    {
        if (M.containsKey(arr[i] & X))
            M.put((arr[i] & X),
             M.get(arr[i] & X) + 1);
        else
            M.put(arr[i] & X, 1);
    }
 
    // Count number of pairs for every
    // element in map using mathematical
    // concept of combination
    for(Integer entry : M.keySet())
    {
        int p = M.get(entry);
 
        // As nC2 = n*(n-1)/2
        count += p * (p - 1) / 2;
    }
 
    // Return the resultant count
    return count;
}
 
// Driver Code
public static void main(String[] args)
{
    int[] arr = { 3, 2, 5, 4, 6, 7 };
    int X = 6;
    int N = arr.length;
     
    System.out.print(countOfPairs(arr, N, X));
}
}
 
// This code is contributed by ukasp

蟒蛇3

# Python3 program for the above approach
 
# Function to find the number of pairs
# that satisfy the given criteria i.e.,
# i < j and (arr[i]^arr[j] )&X is 0
def countOfPairs(arr, N, X):
     
    # Stores the resultant count
    # of pairs
    count = 0
 
    # Initialize the dictionary M
    M = dict()
     
    # Populate the map
    for i in range(0, N):
        k = arr[i] & X
        if k in M:
            M[k] += 1
        else:
            M[k] = 1
             
    # Count number of pairs for every
    # element in map using mathematical
    # concept of combination
    for m in M.keys():
        p = M[m]
         
        # As nC2 = n*(n-1)/2
        count += p * (p - 1) // 2
         
    # Return the resultant count
    return count
 
# Driver Code
if __name__ == '__main__':
 
    arr = [ 3, 2, 5, 4, 6, 7 ]
    X = 6
    N = len(arr)
 
    print(countOfPairs(arr, N, X))
 
# This code is contributed by MuskanKalra1

C#

// C# program for the above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Function to find the number of pairs
// that satisfy the given criteria i.e.,
// i < j and (arr[i]^arr[j] )&X is 0
static int countOfPairs(int []arr, int N, int X)
{
   
    // Stores the resultant count
    // of pairs
    int count = 0;
 
    // Initializing the map M
    Dictionary M = new Dictionary();
 
    // Populating the map
    for (int i = 0; i < N; i++) {
        if(M.ContainsKey(arr[i] & X))
           M[(arr[i] & X)]++;
        else
           M.Add(arr[i] & X,1);
    }
 
    // Count number of pairs for every
    // element in map using mathematical
    // concept of combination
    foreach(KeyValuePair entry in M)
    {
         int p = entry.Value;
 
        // As nC2 = n*(n-1)/2
        count += p * (p - 1) / 2;
    }
 
    // Return the resultant count
    return count;
}
 
// Driver Code
public static void Main()
{
    int []arr = { 3, 2, 5, 4, 6, 7 };
    int X = 6;
    int N = arr.Length;
    Console.Write(countOfPairs(arr, N, X));
}
}
 
// This code is contributed by ipg2016107.

Javascript


输出:
3

时间复杂度: O(N)  
辅助空间: O(N)

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程