📌  相关文章
📜  计算数组子集的不同可能的按位异或值

📅  最后修改于: 2021-09-22 09:40:53             🧑  作者: Mango

给定一个由N 个整数组成的数组arr[] ,任务是找到集合S的大小,使得数组arr[]的任何子集的按位异或存在于集合S 中

例子:

朴素方法:最简单的方法是生成给定数组arr[] 的所有可能的非空子集,并将所有子集的按位异或存储在一个集合中。生成所有子集后,打印得到的集合的大小作为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
 
#include 
using namespace std;
 
// Stores the Bitwise XOR
// of every possible subset
unordered_set s;
 
// Function to generate all
// combinations of subsets and
// store their Bitwise XOR in set S
void countXOR(int arr[], int comb[],
              int start, int end,
              int index, int r)
{
    // If the end of the
    // subset is reached
    if (index == r) {
 
        // Stores the Bitwise XOR
        // of the current subset
        int new_xor = 0;
 
        // Iterate comb[] to find XOR
        for (int j = 0; j < r; j++) {
            new_xor ^= comb[j];
        }
 
        // Insert the Bitwise
        // XOR of R elements
        s.insert(new_xor);
        return;
    }
 
    // Otherwise, iterate to
    // generate all possible subsets
    for (int i = start;
         i <= end && end - i + 1 >= r - index; i++) {
        comb[index] = arr[i];
 
        // Recursive call for next index
        countXOR(arr, comb, i + 1, end,
                 index + 1, r);
    }
}
 
// Function to find the size of the
// set having Bitwise XOR of all the
// subsets of the given array
void maxSizeSet(int arr[], int N)
{
    // Iterate ove the given array
    for (int r = 2; r <= N; r++) {
        int comb[r + 1];
 
        // Generate all possible subsets
        countXOR(arr, comb, 0, N - 1,
                 0, r);
    }
 
    // Print the size of the set
    cout << s.size() << endl;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    maxSizeSet(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG{
 
// Stores the Bitwise XOR
// of every possible subset
static HashSet s;
 
// Function to generate all
// combinations of subsets and
// store their Bitwise XOR in set S
static void countXOR(int arr[], int comb[],
                     int start, int end,
                     int index, int r)
{
     
    // If the end of the
    // subset is reached
    if (index == r)
    {
         
        // Stores the Bitwise XOR
        // of the current subset
        int new_xor = 0;
 
        // Iterate comb[] to find XOR
        for(int j = 0; j < r; j++)
        {
            new_xor ^= comb[j];
        }
 
        // Insert the Bitwise
        // XOR of R elements
        s.add(new_xor);
        return;
    }
 
    // Otherwise, iterate to
    // generate all possible subsets
    for(int i = start;
            i <= end && end - i + 1 >= r - index;
            i++)
    {
        comb[index] = arr[i];
 
        // Recursive call for next index
        countXOR(arr, comb, i + 1, end, index + 1, r);
    }
}
 
// Function to find the size of the
// set having Bitwise XOR of all the
// subsets of the given array
static void maxSizeSet(int arr[], int N)
{
     
    // Iterate ove the given array
    for(int r = 1; r <= N; r++)
    {
        int comb[] = new int[r + 1];
 
        // Generate all possible subsets
        countXOR(arr, comb, 0, N - 1, 0, r);
    }
 
    // Print the size of the set
    System.out.println(s.size());
}
 
// Driver Code
public static void main(String[] args)
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int N = arr.length;
 
    // Initialize set
    s = new HashSet<>();
 
    // Function Call
    maxSizeSet(arr, N);
}
}
 
// This code is contributed by Kingash


Python3
# Python3 program for the above approach
 
# Stores the Bitwise XOR
# of every possible subset
s = set([])
  
# Function to generate all
# combinations of subsets and
# store their Bitwise XOR in set S
def countXOR(arr, comb, start, end, index, r):
 
    # If the end of the
    # subset is reached
    if (index == r) :
  
        # Stores the Bitwise XOR
        # of the current subset
        new_xor = 0
  
        # Iterate comb[] to find XOR
        for j in range(r):
            new_xor ^= comb[j]
  
        # Insert the Bitwise
        # XOR of R elements
        s.add(new_xor)
        return
  
    # Otherwise, iterate to
    # generate all possible subsets
    i = start
    while i <= end and (end - i + 1) >= (r - index):
        comb[index] = arr[i]
  
        # Recursive call for next index
        countXOR(arr, comb, i + 1, end, index + 1, r)
        i += 1
  
# Function to find the size of the
# set having Bitwise XOR of all the
# subsets of the given array
def maxSizeSet(arr, N):
 
    # Iterate ove the given array
    for r in range(2, N + 1):
        comb = [0]*(r + 1)
  
        # Generate all possible subsets
        countXOR(arr, comb, 0, N - 1, 0, r)
  
    # Print the size of the set
    print(len(s))
 
arr = [ 1, 2, 3, 4, 5 ]
N = len(arr)
 
# Function Call
maxSizeSet(arr, N)
 
# This code is contributed by decode2207.


C#
// C# program for the above approach
using System;
using System.Collections.Generic;
public class GFG
{
 
// Stores the Bitwise XOR
// of every possible subset
static HashSet s;
 
// Function to generate all
// combinations of subsets and
// store their Bitwise XOR in set S
static void countXOR(int []arr, int []comb,
                     int start, int end,
                     int index, int r)
{
     
    // If the end of the
    // subset is reached
    if (index == r)
    {
         
        // Stores the Bitwise XOR
        // of the current subset
        int new_xor = 0;
 
        // Iterate comb[] to find XOR
        for(int j = 0; j < r; j++)
        {
            new_xor ^= comb[j];
        }
 
        // Insert the Bitwise
        // XOR of R elements
        s.Add(new_xor);
        return;
    }
 
    // Otherwise, iterate to
    // generate all possible subsets
    for(int i = start;
            i <= end && end - i + 1 >= r - index;
            i++)
    {
        comb[index] = arr[i];
 
        // Recursive call for next index
        countXOR(arr, comb, i + 1, end, index + 1, r);
    }
}
 
// Function to find the size of the
// set having Bitwise XOR of all the
// subsets of the given array
static void maxSizeSet(int []arr, int N)
{
     
    // Iterate ove the given array
    for(int r = 1; r <= N; r++)
    {
        int []comb = new int[r + 1];
 
        // Generate all possible subsets
        countXOR(arr, comb, 0, N - 1, 0, r);
    }
 
    // Print the size of the set
    Console.WriteLine(s.Count);
}
 
// Driver Code
public static void Main(String[] args)
{
    int []arr = { 1, 2, 3, 4, 5 };
    int N = arr.Length;
 
    // Initialize set
    s = new HashSet();
 
    // Function Call
    maxSizeSet(arr, N);
}
}
 
// This code is contributed by Amit Katiyar


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
 
int const size = 20;
 
// Stores the mask of the vector
int dp[size];
 
// Stores the current size of dp[]
int ans;
 
// Function to store the
// mask of given integer
void insertVector(int mask)
{
    // Iterate over the range [0, 20]
    for (int i = 0; i < 20; i++) {
 
        // If i-th bit 0
        if ((mask & 1 << i) == 0)
            continue;
 
        // If dp[i] is zero
        if (!dp[i]) {
 
            // Store the position in dp
            dp[i] = mask;
 
            // Increment the answer
            ++ans;
 
            // Return from the loop
            return;
        }
 
        // mask = mask XOR dp[i]
        mask ^= dp[i];
    }
}
 
// Function to find the size of the
// set having Bitwise XOR of all the
// subset of the given array
void maxSizeSet(int arr[], int N)
{
    // Traverse the array
    for (int i = 0; i < N; i++) {
        insertVector(arr[i]);
    }
 
    // Print the answer
    cout << (1 << ans) << endl;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    maxSizeSet(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
class GFG{
  final static int size = 20;
 
  // Stores the mask of the vector
  static int[] dp = new int[size];
 
  // Stores the current size of dp[]
  static int ans;
 
  // Function to store the
  // mask of given integer
  static void insertVector(int mask)
  {
    // Iterate over the range [0, 20]
    for (int i = 0; i < 20; i++) {
 
      // If i-th bit 0
      if ((mask & 1 << i) == 0)
        continue;
 
      // If dp[i] is zero
      if (dp[i]==0) {
 
        // Store the position in dp
        dp[i] = mask;
 
        // Increment the answer
        ++ans;
 
        // Return from the loop
        return;
      }
 
      // mask = mask XOR dp[i]
      mask ^= dp[i];
    }
  }
 
  // Function to find the size of the
  // set having Bitwise XOR of all the
  // subset of the given array
  static void maxSizeSet(int[] arr, int N)
  {
     
    // Traverse the array
    for (int i = 0; i < N; i++) {
      insertVector(arr[i]);
    }
 
    // Print the answer
    System.out.println(1<


Python3
# Python3 program for the above approach
 
# Stores the mask of the vector
dp = [0]*20
 
# Stores the current 20 of dp[]
ans = 0
 
# Function to store the
# mask of given integer
def insertVector(mask):
    global dp, ans
     
    # Iterate over the range [0, 20]
    for i in range(20):
 
        # If i-th bit 0
        if ((mask & 1 << i) == 0):
            continue
 
        # If dp[i] is zero
        if (not dp[i]):
 
            # Store the position in dp
            dp[i] = mask
 
            # Increment the answer
            ans += 1
 
            # Return from the loop
            return
 
        # mask = mask XOR dp[i]
        mask ^= dp[i]
 
# Function to find the 20 of the
# set having Bitwise XOR of all the
# subset of the given array
def maxSizeSet(arr, N):
   
    # Traverse the array
    for i in range(N):
        insertVector(arr[i])
 
    # Prthe answer
    print ((1 << ans))
 
# Driver Code
if __name__ == '__main__':
    arr = [1, 2, 3, 4, 5]
    N = len(arr)
 
    # Function Call
    maxSizeSet(arr, N)
 
# This code is contributed by mohit kumar 29.


C#
// C# program for the above approach
using System;
 
class GFG{
     
static int size = 20;
 
// Stores the mask of the vector
static int[] dp = new int[size];
 
// Stores the current size of dp[]
static int ans;
 
// Function to store the
// mask of given integer
static void insertVector(int mask)
{
     
    // Iterate over the range [0, 20]
    for(int i = 0; i < 20; i++)
    {
         
        // If i-th bit 0
        if ((mask & 1 << i) == 0)
            continue;
 
        // If dp[i] is zero
        if (dp[i] == 0)
        {
             
            // Store the position in dp
            dp[i] = mask;
 
            // Increment the answer
            ++ans;
 
            // Return from the loop
            return;
        }
 
        // mask = mask XOR dp[i]
        mask ^= dp[i];
    }
}
 
// Function to find the size of the
// set having Bitwise XOR of all the
// subset of the given array
static void maxSizeSet(int[] arr, int N)
{
     
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
        insertVector(arr[i]);
    }
 
    // Print the answer
    Console.WriteLine(1 << ans);
}
 
// Driver code
public static void Main(string[] args)
{
    int[] arr = { 1, 2, 3, 4, 5 };
    int N = arr.Length;
 
    // Function Call
    maxSizeSet(arr, N);
}
}
 
// This code is contributed by ukasp


Javascript


输出:
8

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

高效的方法:可以通过使用贪婪方法和高斯消除来优化上述方法。请按照以下步骤解决问题:

  • 初始化一个辅助数组,比如大小为20 的dp[] 它存储每个数组元素的掩码并用0初始化它。
  • 初始化一个变量,比如ans0 ,以存储数组dp[]的大小。
  • 遍历给定的数组arr[]并对每个数组元素arr[]执行以下步骤:
    • 初始化一个变量,比如掩码arr[i] ,以检查最高有效设置位的位置。
    • 如果设置了arr[i]右侧的i 位并且dp[i]0 ,则将数组dp[i]更新为2 i并将ans的值增加1并退出循环。
    • 否则,将掩码的值更新为掩码dp[i]的按位异或。
  • 完成上述步骤后,打印2 ans的值作为所需元素集的结果大小。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
int const size = 20;
 
// Stores the mask of the vector
int dp[size];
 
// Stores the current size of dp[]
int ans;
 
// Function to store the
// mask of given integer
void insertVector(int mask)
{
    // Iterate over the range [0, 20]
    for (int i = 0; i < 20; i++) {
 
        // If i-th bit 0
        if ((mask & 1 << i) == 0)
            continue;
 
        // If dp[i] is zero
        if (!dp[i]) {
 
            // Store the position in dp
            dp[i] = mask;
 
            // Increment the answer
            ++ans;
 
            // Return from the loop
            return;
        }
 
        // mask = mask XOR dp[i]
        mask ^= dp[i];
    }
}
 
// Function to find the size of the
// set having Bitwise XOR of all the
// subset of the given array
void maxSizeSet(int arr[], int N)
{
    // Traverse the array
    for (int i = 0; i < N; i++) {
        insertVector(arr[i]);
    }
 
    // Print the answer
    cout << (1 << ans) << endl;
}
 
// Driver Code
int main()
{
    int arr[] = { 1, 2, 3, 4, 5 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    maxSizeSet(arr, N);
 
    return 0;
}

Java

// Java program for the above approach
class GFG{
  final static int size = 20;
 
  // Stores the mask of the vector
  static int[] dp = new int[size];
 
  // Stores the current size of dp[]
  static int ans;
 
  // Function to store the
  // mask of given integer
  static void insertVector(int mask)
  {
    // Iterate over the range [0, 20]
    for (int i = 0; i < 20; i++) {
 
      // If i-th bit 0
      if ((mask & 1 << i) == 0)
        continue;
 
      // If dp[i] is zero
      if (dp[i]==0) {
 
        // Store the position in dp
        dp[i] = mask;
 
        // Increment the answer
        ++ans;
 
        // Return from the loop
        return;
      }
 
      // mask = mask XOR dp[i]
      mask ^= dp[i];
    }
  }
 
  // Function to find the size of the
  // set having Bitwise XOR of all the
  // subset of the given array
  static void maxSizeSet(int[] arr, int N)
  {
     
    // Traverse the array
    for (int i = 0; i < N; i++) {
      insertVector(arr[i]);
    }
 
    // Print the answer
    System.out.println(1<

蟒蛇3

# Python3 program for the above approach
 
# Stores the mask of the vector
dp = [0]*20
 
# Stores the current 20 of dp[]
ans = 0
 
# Function to store the
# mask of given integer
def insertVector(mask):
    global dp, ans
     
    # Iterate over the range [0, 20]
    for i in range(20):
 
        # If i-th bit 0
        if ((mask & 1 << i) == 0):
            continue
 
        # If dp[i] is zero
        if (not dp[i]):
 
            # Store the position in dp
            dp[i] = mask
 
            # Increment the answer
            ans += 1
 
            # Return from the loop
            return
 
        # mask = mask XOR dp[i]
        mask ^= dp[i]
 
# Function to find the 20 of the
# set having Bitwise XOR of all the
# subset of the given array
def maxSizeSet(arr, N):
   
    # Traverse the array
    for i in range(N):
        insertVector(arr[i])
 
    # Prthe answer
    print ((1 << ans))
 
# Driver Code
if __name__ == '__main__':
    arr = [1, 2, 3, 4, 5]
    N = len(arr)
 
    # Function Call
    maxSizeSet(arr, N)
 
# This code is contributed by mohit kumar 29.

C#

// C# program for the above approach
using System;
 
class GFG{
     
static int size = 20;
 
// Stores the mask of the vector
static int[] dp = new int[size];
 
// Stores the current size of dp[]
static int ans;
 
// Function to store the
// mask of given integer
static void insertVector(int mask)
{
     
    // Iterate over the range [0, 20]
    for(int i = 0; i < 20; i++)
    {
         
        // If i-th bit 0
        if ((mask & 1 << i) == 0)
            continue;
 
        // If dp[i] is zero
        if (dp[i] == 0)
        {
             
            // Store the position in dp
            dp[i] = mask;
 
            // Increment the answer
            ++ans;
 
            // Return from the loop
            return;
        }
 
        // mask = mask XOR dp[i]
        mask ^= dp[i];
    }
}
 
// Function to find the size of the
// set having Bitwise XOR of all the
// subset of the given array
static void maxSizeSet(int[] arr, int N)
{
     
    // Traverse the array
    for(int i = 0; i < N; i++)
    {
        insertVector(arr[i]);
    }
 
    // Print the answer
    Console.WriteLine(1 << ans);
}
 
// Driver code
public static void Main(string[] args)
{
    int[] arr = { 1, 2, 3, 4, 5 };
    int N = arr.Length;
 
    // Function Call
    maxSizeSet(arr, N);
}
}
 
// This code is contributed by ukasp

Javascript


输出:
8

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

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