📌  相关文章
📜  两个等长子集的所有元素的按位异或的最大和

📅  最后修改于: 2021-09-17 16:13:27             🧑  作者: Mango

给定一个由N 个整数组成的数组arr[] ,其中N是偶数。任务是将给定的N 个整数分成两个相等的子集,使得两个子集的所有元素的按位异或之和最大。

例子:

朴素的方法:这个想法是检查N/2对的每个可能的分布。打印最大的两个子集的所有元素之和的按位异或。

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

高效的方法:为了优化上述方法,想法是使用使用位掩码的动态编程。请按照以下步骤解决问题:

  1. 最初,位掩码为 0,如果设置了该位,则已经选择了该对。
  2. 遍历所有可能的对并检查是否可以选择一对,即i 和 j的位未在掩码中设置:
    • 如果可以采用该对,则找到当前对的按位异或和并递归检查下一个对。
    • 否则检查下一对元素。
  3. 在上述步骤中为每个递归调用不断更新最大 XOR 对总和。
  4. 打印dp[mask] 中存储的所有可能对的最大值。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include
using namespace std;
 
// Function that finds the maximum
// Bitwise XOR sum of the two subset
int xorSum(int a[], int n,
           int mask, int dp[])
{
  // Check if the current state is
  // already computed
  if (dp[mask] != -1)
  {
    return dp[mask];
  }
 
  // Initialize answer to minimum value
  int max_value = 0;
 
  // Iterate through all possible pairs
  for (int i = 0; i < n; i++)
  {
    for (int j = i + 1; j < n; j++)
    {
 
      // Check whether ith bit and
      // jth bit of mask is not
      // set then pick the pair
      if (i != j &&
         (mask & (1 << i)) == 0 &&
         (mask & (1 << j)) == 0)
      {
 
        // For all possible pairs
        // find maximum value pick
        // current a[i], a[j] and
        // set i, j th bits in mask
        max_value = max(max_value, (a[i] ^ a[j]) +
                        xorSum(a, n, (mask | (1 << i) |
                                               (1 << j)), dp));
      }
    }
  }
 
  // Store the maximum value
  // and return the answer
  return dp[mask] = max_value;
}
 
// Driver Code
int main()
{
   int n = 4;
 
   // Given array arr[]
   int arr[] = { 1, 2, 3, 4 };
 
   // Declare Initialize the dp states
   int dp[(1 << n) + 5];
   memset(dp, -1, sizeof(dp));
 
   // Function Call
   cout << (xorSum(arr, n, 0, dp));
}
 
// This code is contributed by Rohit_ranjan


Java
// Java program for the above approach
import java.util.*;
import java.io.*;
 
public class GFG {
 
    // Function that finds the maximum
    // Bitwise XOR sum of the two subset
    public static int xorSum(int a[], int n,
                             int mask, int[] dp)
    {
        // Check if the current state is
        // already computed
        if (dp[mask] != -1) {
            return dp[mask];
        }
 
        // Initialize answer to minimum value
        int max_value = 0;
 
        // Iterate through all possible pairs
        for (int i = 0; i < n; i++) {
 
            for (int j = i + 1; j < n; j++) {
 
                // Check whether ith bit and
                // jth bit of mask is not
                // set then pick the pair
                if (i != j
                    && (mask & (1 << i)) == 0
                    && (mask & (1 << j)) == 0) {
 
                    // For all possible pairs
                    // find maximum value pick
                    // current a[i], a[j] and
                    // set i, j th bits in mask
                    max_value = Math.max(
                        max_value,
                        (a[i] ^ a[j])
                            + xorSum(a, n,
                                     (mask | (1 << i)
                                      | (1 << j)),
                                     dp));
                }
            }
        }
 
        // Store the maximum value
        // and return the answer
        return dp[mask] = max_value;
    }
 
    // Driver Code
    public static void main(String args[])
    {
        int n = 4;
 
        // Given array arr[]
        int arr[] = { 1, 2, 3, 4 };
 
        // Declare Initialize the dp states
        int dp[] = new int[(1 << n) + 5];
        Arrays.fill(dp, -1);
 
        // Function Call
        System.out.println(xorSum(arr, n, 0, dp));
    }
}


Python3
# Python3 program to implement
# the above approach
 
# Function that finds the maximum
# Bitwise XOR sum of the two subset
def xorSum(a, n, mask, dp):
 
    # Check if the current state is
    # already computed
    if(dp[mask] != -1):
        return dp[mask]
 
    # Initialize answer to minimum value
    max_value = 0
 
    # Iterate through all possible pairs
    for i in range(n):
        for j in range(i + 1, n):
 
            # Check whether ith bit and
            # jth bit of mask is not
            # set then pick the pair
            if(i != j and
              (mask & (1 << i)) == 0 and
              (mask & (1 << j)) == 0):
 
                # For all possible pairs
                # find maximum value pick
                # current a[i], a[j] and
                # set i, j th bits in mask
                max_value = max(max_value,
                               (a[i] ^ a[j]) +
                                xorSum(a, n,
                                (mask | (1 << i) |
                                (1 << j)), dp))
 
    # Store the maximum value
    # and return the answer
    dp[mask] = max_value
 
    return dp[mask]
 
# Driver Code
n = 4
 
# Given array arr[]
arr = [ 1, 2, 3, 4 ]
 
# Declare Initialize the dp states
dp = [-1] * ((1 << n) + 5)
 
# Function call
print(xorSum(arr, n, 0, dp))
 
# This code is contributed by Shivam Singh


C#
// C# program for the above approach
using System;
 
class GFG{
 
// Function that finds the maximum
// Bitwise XOR sum of the two subset
public static int xorSum(int []a, int n,
                         int mask, int[] dp)
{
     
    // Check if the current state is
    // already computed
    if (dp[mask] != -1)
    {
        return dp[mask];
    }
 
    // Initialize answer to minimum value
    int max_value = 0;
 
    // Iterate through all possible pairs
    for(int i = 0; i < n; i++)
    {
        for(int j = i + 1; j < n; j++)
        {
             
            // Check whether ith bit and
            // jth bit of mask is not
            // set then pick the pair
            if (i != j &&
               (mask & (1 << i)) == 0 &&
               (mask & (1 << j)) == 0)
            {
 
                // For all possible pairs
                // find maximum value pick
                // current a[i], a[j] and
                // set i, j th bits in mask
                max_value = Math.Max(
                            max_value,
                            (a[i] ^ a[j]) +
                            xorSum(a, n, (mask |
                            (1 << i) | (1 << j)), dp));
            }
        }
    }
 
    // Store the maximum value
    // and return the answer
    return dp[mask] = max_value;
}
 
// Driver Code
public static void Main(String []args)
{
    int n = 4;
 
    // Given array []arr
    int []arr = { 1, 2, 3, 4 };
 
    // Declare Initialize the dp states
    int []dp = new int[(1 << n) + 5];
    for(int i = 0; i < dp.Length; i++)
        dp[i] = -1;
 
    // Function call
    Console.WriteLine(xorSum(arr, n, 0, dp));
}
}
 
// This code is contributed by amal kumar choubey


Javascript


输出:
10

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

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