📌  相关文章
📜  计算总和仅由设置位组成的对

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

给定一个由N 个整数组成的数组arr[] ,任务是在给定数组中找到其总和包含所有设置位的无序对的计数。

例子:

朴素的方法:这个想法是生成所有可能的对并检查它们的总和是否设置了所有位。如果发现为真,则在结果计数中计算该对。检查所有对后打印计数。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to check if the number num
// has all set bits or not
bool allSetBits(int num)
{
    // Find total bitsac
    int totalBits = log2(num) + 1;
 
    // Find count of set bit
    int setBits = __builtin_popcount(num);
 
    // Return true if all bit are set
    if (totalBits == setBits)
        return true;
    else
        return false;
}
 
// Function that find the count of
// pairs whose sum has all set bits
int countPairs(int arr[], int n)
{
    // Stores the count of pairs
    int ans = 0;
 
    // Generate all the pairs
    for (int i = 0; i < n; i++) {
 
        for (int j = i + 1; j < n; j++) {
 
            // Find the sum of current pair
            int sum = arr[i] + arr[j];
 
            // If all bits are set
            if (allSetBits(sum))
                ans++;
        }
    }
 
    // Return the final count
    return ans;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 5, 10 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << countPairs(arr, N);
 
    return 0;
}


Java
// Java program for the
// above approach
import java.util.*;
class GFG{
 
// Function to check if the
// number num has all set
// bits or not
static boolean allSetBits(int num)
{
  // Find total bitsac
  int totalBits = (int)Math.log(num) + 1;
 
  // Find count of set bit
  int setBits = Integer.bitCount(num);
 
  // Return true if all
  // bit are set
  if (totalBits == setBits)
    return true;
  else
    return false;
}
 
// Function that find the
// count of pairs whose sum
// has all set bits
static int countPairs(int arr[],
                      int n)
{
  // Stores the count
  // of pairs
  int ans = 0;
 
  // Generate all the pairs
  for (int i = 0; i < n; i++)
  {
    for (int j = i + 1; j < n; j++)
    {
      // Find the sum of
      // current pair
      int sum = arr[i] + arr[j];
 
      // If all bits are set
      if (allSetBits(sum))
        ans++;
    }
  }
 
  // Return the final count
  return ans;
}
 
// Driver Code
public static void main(String[] args)
{
  int arr[] = {1, 2, 5, 10};
  int N = arr.length;
 
  // Function Call
  System.out.print(countPairs(arr, N));
}
}
 
// This code is contributed by gauravrajput1


Python3
# Python3 program for the above approach
from math import log2
 
# Function to check if the number num
# has all set bits or not
def allSetBits(num):
     
    # Find total bits
    totalBits = int(log2(num) + 1)
 
    # Find count of set bit
    setBits = bin(num).count('1')
 
    # Return true if all bit are set
    if (totalBits == setBits):
        return True
    else:
        return False
 
# Function that find the count of
# pairs whose sum has all set bits
def countPairs(arr, n):
     
    # Stores the count of pairs
    ans = 0
 
    # Generate all the pairs
    for i in range(n):
        for j in range(i + 1, n):
 
            # Find the sum of current pair
            sum = arr[i] + arr[j]
 
            # If all bits are set
            if (allSetBits(sum)):
                ans += 1
 
    # Return the final count
    return ans
 
# Driver Code
if __name__ == '__main__':
     
    arr = [ 1, 2, 5, 10 ]
    N = len(arr)
 
    # Function Call
    print(countPairs(arr, N))
 
# This code is contributed by mohit kumar 29


C#
// C# program for the
// above approach
using System;
class GFG{
 
static int countSetBits(int n)
{
  int count = 0;
   
  while (n > 0)
  {
    count += n & 1;
    n >>= 1;
  }
  return count;
}
   
// Function to check if the
// number num has all set
// bits or not
static bool allSetBits(int num)
{
  // Find total bitsac
  int totalBits = (int)Math.Log(num) + 1;
 
  // Find count of set bit
  int setBits = countSetBits(num);
 
  // Return true if all
  // bit are set
  if (totalBits == setBits)
    return true;
  else
    return false;
}
 
// Function that find the
// count of pairs whose sum
// has all set bits
static int countPairs(int []arr,
                      int n)
{
  // Stores the count
  // of pairs
  int ans = 0;
 
  // Generate all the pairs
  for (int i = 0; i < n; i++)
  {
    for (int j = i + 1; j < n; j++)
    {
      // Find the sum of
      // current pair
      int sum = arr[i] + arr[j];
 
      // If all bits are set
      if (allSetBits(sum))
        ans++;
    }
  }
 
  // Return the readonly count
  return ans;
}
 
// Driver Code
public static void Main(String[] args)
{
  int []arr = {1, 2, 5, 10};
  int N = arr.Length;
 
  // Function Call
  Console.Write(countPairs(arr, N));
}
}
 
// This code is contributed by Princi Singh


Javascript


C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Store numbers having all set bits
vector setArray;
 
// Store frequency of values in arr[]
map mp;
 
// Function to fill setArray[] with
// numbers that have all set bits
void fillsetArray()
{
    for (int i = 1; i < 31; i++) {
        setArray.push_back((1 << i) - 1);
    }
}
 
// Function to find the count of pairs
// whose sum contains all set bits
int countPairs(int arr[], int n)
{
    // Stores the count of pairs
    int ans = 0;
 
    fillsetArray();
 
    // Hash the values of arr[] in mp
    for (int i = 0; i < n; i++)
        mp[arr[i]]++;
 
    // Traverse the array arr[]
    for (int i = 0; i < n; i++) {
 
        // Iterate over the range [0, 30]
        for (int j = 0; j < 30; j++) {
 
            // Find the difference
            int value = setArray[j] - arr[i];
 
            // Update the final count
            ans += mp[value];
        }
    }
 
    // Return the final count
    return ans / 2;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 5, 10 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << countPairs(arr, N);
 
    return 0;
}


Java
// Java program for the
// above approach
import java.util.*;
class GFG{
 
// Store numbers having
// all set bits
static Vector setArray =
              new Vector<>();
 
// Store frequency of
// values in arr[]
static HashMap mp = new HashMap();
   
// Function to fill setArray[]
// with numbers that have all
// set bits
static void fillsetArray()
{
  for (int i = 1; i < 31; i++)
  {
    setArray.add((1 << i) - 1);
  }
}
 
// Function to find the count
// of pairs whose sum contains
// all set bits
static int countPairs(int arr[],
                      int n)
{
  // Stores the count
  // of pairs
  int ans = 0;
 
  fillsetArray();
 
  // Hash the values of
  // arr[] in mp
  for (int i = 0; i < n; i++)
    if(mp.containsKey(arr[i]))
    {
      mp.put(arr[i],
             mp.get(arr[i]) + 1);
    }
    else
    {
      mp.put(arr[i], 1);
    }
 
  // Traverse the array arr[]
  for (int i = 0; i < n; i++)
  {
    // Iterate over the range
    // [0, 30]
    for (int j = 0; j < 30; j++)
    {
      // Find the difference
      int value = setArray.get(j) -
        arr[i];
 
      // Update the final count
      if(mp.containsKey(value))
        ans += mp.get(value);
    }
  }
 
  // Return the final count
  return ans / 2;
}
 
// Driver Code
public static void main(String[] args)
{
  int arr[] = {1, 2, 5, 10};
  int N = arr.length;
 
  // Function Call
  System.out.print(countPairs(arr, N));
}
}
 
// This code is contributed by Rajput-Ji


Python3
# Python3 program for the
# above approach
from collections import defaultdict
 
# Store numbers having
# all set bits
setArray = []
 
# Store frequency of values
# in arr[]
mp = defaultdict (int)
 
# Function to fill setArray[] with
# numbers that have all set bits
def fillsetArray():
 
    for i in range (1, 31):
        setArray.append((1 << i) - 1)
     
# Function to find the
# count of pairs whose sum
# contains all set bits
def countPairs(arr, n):
 
    # Stores the count of pairs
    ans = 0
 
    fillsetArray()
 
    # Hash the values of
    # arr[] in mp
    for i in range (n):
        mp[arr[i]] += 1
 
    # Traverse the array arr[]
    for i in range (n):
 
        # Iterate over the range
        # [0, 30]
        for j in range (30):
 
            # Find the difference
            value = setArray[j] - arr[i]
 
            # Update the final count
            ans += mp[value]
        
    # Return the final count
    return ans // 2
 
# Driver Code
if __name__ == "__main__":
   
    arr = [1, 2, 5, 10]
    N = len(arr)
 
    # Function Call
    print (countPairs(arr, N))
 
# This code is contributed by Chitranayal


C#
// C# program for the
// above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Store numbers having
// all set bits
static List setArray = new List();
 
// Store frequency of
// values in []arr
static Dictionary mp = new Dictionary();
   
// Function to fill setArray[]
// with numbers that have all
// set bits
static void fillsetArray()
{
  for(int i = 1; i < 31; i++)
  {
    setArray.Add((1 << i) - 1);
  }
}
 
// Function to find the count
// of pairs whose sum contains
// all set bits
static int countPairs(int []arr,
                      int n)
{
   
  // Stores the count
  // of pairs
  int ans = 0;
 
  fillsetArray();
 
  // Hash the values of
  // []arr in mp
  for(int i = 0; i < n; i++)
    if(mp.ContainsKey(arr[i]))
    {
      mp.Add(arr[i],
          mp[arr[i]] + 1);
    }
    else
    {
      mp.Add(arr[i], 1);
    }
 
  // Traverse the array []arr
  for(int i = 0; i < n; i++)
  {
     
    // Iterate over the range
    // [0, 30]
    for(int j = 0; j < 30; j++)
    {
       
      // Find the difference
      int value = setArray[j] -
                       arr[i];
 
      // Update the readonly count
      if (mp.ContainsKey(value))
        ans += mp[value];
    }
  }
   
  // Return the readonly count
  return ans / 2;
}
 
// Driver Code
public static void Main(String[] args)
{
  int []arr = {1, 2, 5, 10};
  int N = arr.Length;
 
  // Function Call
  Console.Write(countPairs(arr, N));
}
}
 
// This code is contributed by Princi Singh


Javascript


输出
3

时间复杂度: O(N 2 log N),其中 N 是给定数组的大小。
辅助空间: O(N)

有效方法:关键观察是只有从0N 的log N 个数字包含所有设置位。此属性可用于优化上述方法。请按照以下步骤解决问题:

  • 将所有log(MAX_INTEGER)元素存储在数组setArray[] 中
  • 在 Map 数据结构中映射数组arr[] 的所有元素,其中元素是键,其频率是值。
  • [0, N – 1]范围内遍历给定数组arr[]并在嵌套循环中遍历数组setArray[]j = 0 到 log(MAX_INTEGER)并通过map[setArray[j] – arr[i]递增ans ]]其中ans存储所需对的总数。
  • 因为有重复计算,因为(a, b)(b, a)被计算了两次。因此,打印ans/2的值以获得所需的计数。

下面是上述方法的实现:

C++

// C++ program for the above approach
 
#include 
using namespace std;
 
// Store numbers having all set bits
vector setArray;
 
// Store frequency of values in arr[]
map mp;
 
// Function to fill setArray[] with
// numbers that have all set bits
void fillsetArray()
{
    for (int i = 1; i < 31; i++) {
        setArray.push_back((1 << i) - 1);
    }
}
 
// Function to find the count of pairs
// whose sum contains all set bits
int countPairs(int arr[], int n)
{
    // Stores the count of pairs
    int ans = 0;
 
    fillsetArray();
 
    // Hash the values of arr[] in mp
    for (int i = 0; i < n; i++)
        mp[arr[i]]++;
 
    // Traverse the array arr[]
    for (int i = 0; i < n; i++) {
 
        // Iterate over the range [0, 30]
        for (int j = 0; j < 30; j++) {
 
            // Find the difference
            int value = setArray[j] - arr[i];
 
            // Update the final count
            ans += mp[value];
        }
    }
 
    // Return the final count
    return ans / 2;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 5, 10 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    cout << countPairs(arr, N);
 
    return 0;
}

Java

// Java program for the
// above approach
import java.util.*;
class GFG{
 
// Store numbers having
// all set bits
static Vector setArray =
              new Vector<>();
 
// Store frequency of
// values in arr[]
static HashMap mp = new HashMap();
   
// Function to fill setArray[]
// with numbers that have all
// set bits
static void fillsetArray()
{
  for (int i = 1; i < 31; i++)
  {
    setArray.add((1 << i) - 1);
  }
}
 
// Function to find the count
// of pairs whose sum contains
// all set bits
static int countPairs(int arr[],
                      int n)
{
  // Stores the count
  // of pairs
  int ans = 0;
 
  fillsetArray();
 
  // Hash the values of
  // arr[] in mp
  for (int i = 0; i < n; i++)
    if(mp.containsKey(arr[i]))
    {
      mp.put(arr[i],
             mp.get(arr[i]) + 1);
    }
    else
    {
      mp.put(arr[i], 1);
    }
 
  // Traverse the array arr[]
  for (int i = 0; i < n; i++)
  {
    // Iterate over the range
    // [0, 30]
    for (int j = 0; j < 30; j++)
    {
      // Find the difference
      int value = setArray.get(j) -
        arr[i];
 
      // Update the final count
      if(mp.containsKey(value))
        ans += mp.get(value);
    }
  }
 
  // Return the final count
  return ans / 2;
}
 
// Driver Code
public static void main(String[] args)
{
  int arr[] = {1, 2, 5, 10};
  int N = arr.length;
 
  // Function Call
  System.out.print(countPairs(arr, N));
}
}
 
// This code is contributed by Rajput-Ji

蟒蛇3

# Python3 program for the
# above approach
from collections import defaultdict
 
# Store numbers having
# all set bits
setArray = []
 
# Store frequency of values
# in arr[]
mp = defaultdict (int)
 
# Function to fill setArray[] with
# numbers that have all set bits
def fillsetArray():
 
    for i in range (1, 31):
        setArray.append((1 << i) - 1)
     
# Function to find the
# count of pairs whose sum
# contains all set bits
def countPairs(arr, n):
 
    # Stores the count of pairs
    ans = 0
 
    fillsetArray()
 
    # Hash the values of
    # arr[] in mp
    for i in range (n):
        mp[arr[i]] += 1
 
    # Traverse the array arr[]
    for i in range (n):
 
        # Iterate over the range
        # [0, 30]
        for j in range (30):
 
            # Find the difference
            value = setArray[j] - arr[i]
 
            # Update the final count
            ans += mp[value]
        
    # Return the final count
    return ans // 2
 
# Driver Code
if __name__ == "__main__":
   
    arr = [1, 2, 5, 10]
    N = len(arr)
 
    # Function Call
    print (countPairs(arr, N))
 
# This code is contributed by Chitranayal

C#

// C# program for the
// above approach
using System;
using System.Collections.Generic;
 
class GFG{
 
// Store numbers having
// all set bits
static List setArray = new List();
 
// Store frequency of
// values in []arr
static Dictionary mp = new Dictionary();
   
// Function to fill setArray[]
// with numbers that have all
// set bits
static void fillsetArray()
{
  for(int i = 1; i < 31; i++)
  {
    setArray.Add((1 << i) - 1);
  }
}
 
// Function to find the count
// of pairs whose sum contains
// all set bits
static int countPairs(int []arr,
                      int n)
{
   
  // Stores the count
  // of pairs
  int ans = 0;
 
  fillsetArray();
 
  // Hash the values of
  // []arr in mp
  for(int i = 0; i < n; i++)
    if(mp.ContainsKey(arr[i]))
    {
      mp.Add(arr[i],
          mp[arr[i]] + 1);
    }
    else
    {
      mp.Add(arr[i], 1);
    }
 
  // Traverse the array []arr
  for(int i = 0; i < n; i++)
  {
     
    // Iterate over the range
    // [0, 30]
    for(int j = 0; j < 30; j++)
    {
       
      // Find the difference
      int value = setArray[j] -
                       arr[i];
 
      // Update the readonly count
      if (mp.ContainsKey(value))
        ans += mp[value];
    }
  }
   
  // Return the readonly count
  return ans / 2;
}
 
// Driver Code
public static void Main(String[] args)
{
  int []arr = {1, 2, 5, 10};
  int N = arr.Length;
 
  // Function Call
  Console.Write(countPairs(arr, N));
}
}
 
// This code is contributed by Princi Singh

Javascript


输出
3

时间复杂度: O(N*32),其中 N 是给定数组的大小。
辅助空间: O(N)

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