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

📅  最后修改于: 2021-04-27 17:37:00             🧑  作者: Mango

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

例子:

天真的方法:这个想法是检查N / 2对的每个可能的分布。打印两个子集的所有元素的总和的按位XOR,这是最大的。

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

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

  1. 最初,位掩码为0,如果设置了该位,则说明该对已经被选中。
  2. 遍历所有可能的对,并检查是否有可能选择一对,即在掩码中未设置i和j的位:
    • 如果可以接受该对,则找到当前对的按位XOR总和,然后递归检查下一个对。
    • 否则检查下一对元素。
  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


输出:
10


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