📜  计算甚至具有按位XOR的子数组

📅  最后修改于: 2021-05-25 02:28:23             🧑  作者: Mango

给定大小为N的数组arr [] ,任务是从给定数组中按位XOR为偶数的子数组计数。

例子:

天真的方法:解决此问题的最简单方法是生成所有可能的子数组,并检查每个子数组,无论其所有元素的按位XOR是否为偶数。如果发现是偶数,则增加计数。最后,将计数打印为结果。

下面是上述方法的实现:

C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to count the number of
// subarrays having even Bitwise XOR
void evenXorSubarray(int arr[], int n)
{
    // Store the required result
    int ans = 0;
 
    // Generate subarrays with
    // arr[i] as the first element
    for (int i = 0; i < n; i++) {
 
        // Store XOR of current subarray
        int XOR = 0;
 
        // Generate subarrays with
        // arr[j] as the last element
        for (int j = i; j < n; j++) {
 
            // Calculate Bitwise XOR
            // of the current subarray
            XOR = XOR ^ arr[j];
 
            // If XOR is even,
            // increase ans by 1
            if ((XOR & 1) == 0)
                ans++;
        }
    }
 
    // Print the result
    cout << ans;
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 1, 2, 3, 4 };
 
    // Stores the size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    // Function Call
    evenXorSubarray(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
  // Function to count the number of
  // subarrays having even Bitwise XOR
  static void evenXorSubarray(int arr[], int n)
  {
     
    // Store the required result
    int ans = 0;
 
    // Generate subarrays with
    // arr[i] as the first element
    for (int i = 0; i < n; i++) {
 
      // Store XOR of current subarray
      int XOR = 0;
 
      // Generate subarrays with
      // arr[j] as the last element
      for (int j = i; j < n; j++) {
 
        // Calculate Bitwise XOR
        // of the current subarray
        XOR = XOR ^ arr[j];
 
        // If XOR is even,
        // increase ans by 1
        if ((XOR & 1) == 0)
          ans++;
      }
    }
 
    // Print the result
    System.out.println(ans);
  }
 
  // Driver Code
  public static void main(String[] args)
  {
 
    // Given array
    int arr[] = { 1, 2, 3, 4 };
 
    // Stores the size of the array
    int N = arr.length;
    evenXorSubarray(arr, N);
  }
}
 
// This code is contributed by Kingash.


Python3
# Python3 program for the above approach
 
# Function to count the number of
# subarrays having even Bitwise XOR
def evenXorSubarray(arr, n):
   
    # Store the required result
    ans = 0
 
    # Generate subarrays with
    # arr[i] as the first element
    for i in range(n):
 
        # Store XOR of current subarray
        XOR = 0
 
        # Generate subarrays with
        # arr[j] as the last element
        for j in range(i, n):
 
            # Calculate Bitwise XOR
            # of the current subarray
            XOR = XOR ^ arr[j]
 
            # If XOR is even,
            # increase ans by 1
            if ((XOR & 1) == 0):
                ans += 1
 
    # Prthe result
    print (ans)
 
# Driver Code
if __name__ == '__main__':
   
    # Given array
    arr = [1, 2, 3, 4]
 
    # Stores the size of the array
    N = len(arr)
 
    # Function Call
    evenXorSubarray(arr, N)
 
# This code is contributed by mohit kumar 29.


C#
// C# program for the above approach
using System;
class GFG
{
  // Function to count the number of
  // subarrays having even Bitwise XOR
  static void evenXorSubarray(int[] arr, int n)
  {
 
    // Store the required result
    int ans = 0;
 
    // Generate subarrays with
    // arr[i] as the first element
    for (int i = 0; i < n; i++) {
 
      // Store XOR of current subarray
      int XOR = 0;
 
      // Generate subarrays with
      // arr[j] as the last element
      for (int j = i; j < n; j++) {
 
        // Calculate Bitwise XOR
        // of the current subarray
        XOR = XOR ^ arr[j];
 
        // If XOR is even,
        // increase ans by 1
        if ((XOR & 1) == 0)
          ans++;
      }
    }
 
    // Print the result
    Console.WriteLine(ans);
  }
 
  // Driver Code
  public static void Main()
  {
    // Given array
    int[] arr = { 1, 2, 3, 4 };
 
    // Stores the size of the array
    int N = arr.Length;
    evenXorSubarray(arr, N);
  }
}
 
// This code is contributed by souravghosh0416.


Javascript


C++
// C++ program for the above approach
#include 
using namespace std;
 
// Function to count subarrays
// having even Bitwise XOR
void evenXorSubarray(int arr[], int n)
{
    // Store the required result
    int ans = 0;
 
    // Stores count of subarrays
    // with even and odd XOR values
    int freq[] = { 0, 0 };
 
    // Stores Bitwise XOR of
    // current subarray
    int XOR = 0;
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
 
        // Update current Xor
        XOR = XOR ^ arr[i];
 
        // If XOR is even
        if (XOR % 2 == 0) {
 
            // Update ans
            ans += freq[0] + 1;
 
            // Increment count of
            // subarrays with even XOR
            freq[0]++;
        }
        else {
 
            // Otherwise, increment count
            // of subarrays with odd XOR
            ans += freq[1];
            freq[1]++;
        }
    }
 
    // Print the result
    cout << ans;
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 1, 2, 3, 4 };
 
    // Stores the size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    evenXorSubarray(arr, N);
 
    return 0;
}


Java
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
    // Function to count subarrays
    // having even Bitwise XOR
    static void evenXorSubarray(int arr[], int n)
    {
        // Store the required result
        int ans = 0;
 
        // Stores count of subarrays
        // with even and odd XOR values
        int freq[] = { 0, 0 };
 
        // Stores Bitwise XOR of
        // current subarray
        int XOR = 0;
 
        // Traverse the array
        for (int i = 0; i < n; i++) {
 
            // Update current Xor
            XOR = XOR ^ arr[i];
 
            // If XOR is even
            if (XOR % 2 == 0) {
 
                // Update ans
                ans += freq[0] + 1;
 
                // Increment count of
                // subarrays with even XOR
                freq[0]++;
            }
            else {
 
                // Otherwise, increment count
                // of subarrays with odd XOR
                ans += freq[1];
                freq[1]++;
            }
        }
 
        // Print the result
        System.out.println(ans);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Given array
        int arr[] = { 1, 2, 3, 4 };
 
        // Stores the size of the array
        int N = arr.length;
 
        evenXorSubarray(arr, N);
    }
}


Python3
# Python3 program for the above approach
 
# Function to count subarrays
# having even Bitwise XOR
def evenXorSubarray(arr, n):
     
    # Store the required result
    ans = 0
 
    # Stores count of subarrays
    # with even and odd XOR values
    freq = [0] * n
 
    # Stores Bitwise XOR of
    # current subarray
    XOR = 0
 
    # Traverse the array
    for i in range(n):
 
        # Update current Xor
        XOR = XOR ^ arr[i]
 
        # If XOR is even
        if (XOR % 2 == 0):
 
            # Update ans
            ans += freq[0] + 1
 
            # Increment count of
            # subarrays with even XOR
            freq[0] += 1
         
        else:
 
            # Otherwise, increment count
            # of subarrays with odd XOR
            ans += freq[1]
            freq[1] += 1
         
    # Print the result
    print(ans)
 
# Driver Code
 
# Given array
arr = [ 1, 2, 3, 4 ]
 
# Stores the size of the array
N = len(arr)
 
evenXorSubarray(arr, N)
 
# This code is contributed by sanjoy_62


C#
// C# program for the above approach
using System;
class GFG
{
  // Function to count subarrays
  // having even Bitwise XOR
  static void evenXorSubarray(int[] arr, int n)
  {
     
    // Store the required result
    int ans = 0;
 
    // Stores count of subarrays
    // with even and odd XOR values
    int[] freq = { 0, 0 };
 
    // Stores Bitwise XOR of
    // current subarray
    int XOR = 0;
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
 
      // Update current Xor
      XOR = XOR ^ arr[i];
 
      // If XOR is even
      if (XOR % 2 == 0) {
 
        // Update ans
        ans += freq[0] + 1;
 
        // Increment count of
        // subarrays with even XOR
        freq[0]++;
      }
      else {
 
        // Otherwise, increment count
        // of subarrays with odd XOR
        ans += freq[1];
        freq[1]++;
      }
    }
 
    // Print the result
    Console.WriteLine(ans);
  }
 
 
  // Driver Code
  public static void Main(String[] args)
  {
    // Given array
    int[] arr = { 1, 2, 3, 4 };
 
    // Stores the size of the array
    int N = arr.Length;
 
    evenXorSubarray(arr, N);
  }
}
 
// This code is contributed by susmitakundugoaldanga.


Javascript


输出:
4

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

高效的方法:可以基于以下观察来优化上述方法:

因此,该想法是从索引0开始更新具有偶数和奇数XOR值的子数组的数量,同时遍历该数组并相应地更新计数。请按照以下步骤解决问题:

  • 初始化两个变量,例如ansXOR,以存储所需的子数组计数和分别存储子数组的XOR值。
  • 初始化一个数组,说大小为2的freq [] ,其中freq [0]表示具有偶数XOR值的子数组的数量, freq [1]表示具有奇数XOR值的子数组的数量,从索引0开始。
  • 对于每个数组元素,使用变量i遍历数组arr []
    • XOR的值更新为XOR ^ arr [i]
    • 如果XOR为偶数,则将ans的值增加1 + freq [0]
    • freq [0]递增1,因为当子数组{arr [0],i]与其他具有偶数xor值的子数组进行XOR运算时,它将导致偶数XOR值。同样,添加1以考虑整个子数组[0,i]。
    • 同样,如果XOR为奇数,则将ans增加freq [1] ,将freq [1]增加1。
  • 完成上述步骤后,输出ans的值作为结果。

下面是上述方法的实现:

C++

// C++ program for the above approach
#include 
using namespace std;
 
// Function to count subarrays
// having even Bitwise XOR
void evenXorSubarray(int arr[], int n)
{
    // Store the required result
    int ans = 0;
 
    // Stores count of subarrays
    // with even and odd XOR values
    int freq[] = { 0, 0 };
 
    // Stores Bitwise XOR of
    // current subarray
    int XOR = 0;
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
 
        // Update current Xor
        XOR = XOR ^ arr[i];
 
        // If XOR is even
        if (XOR % 2 == 0) {
 
            // Update ans
            ans += freq[0] + 1;
 
            // Increment count of
            // subarrays with even XOR
            freq[0]++;
        }
        else {
 
            // Otherwise, increment count
            // of subarrays with odd XOR
            ans += freq[1];
            freq[1]++;
        }
    }
 
    // Print the result
    cout << ans;
}
 
// Driver Code
int main()
{
    // Given array
    int arr[] = { 1, 2, 3, 4 };
 
    // Stores the size of the array
    int N = sizeof(arr) / sizeof(arr[0]);
 
    evenXorSubarray(arr, N);
 
    return 0;
}

Java

// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;
 
class GFG {
 
    // Function to count subarrays
    // having even Bitwise XOR
    static void evenXorSubarray(int arr[], int n)
    {
        // Store the required result
        int ans = 0;
 
        // Stores count of subarrays
        // with even and odd XOR values
        int freq[] = { 0, 0 };
 
        // Stores Bitwise XOR of
        // current subarray
        int XOR = 0;
 
        // Traverse the array
        for (int i = 0; i < n; i++) {
 
            // Update current Xor
            XOR = XOR ^ arr[i];
 
            // If XOR is even
            if (XOR % 2 == 0) {
 
                // Update ans
                ans += freq[0] + 1;
 
                // Increment count of
                // subarrays with even XOR
                freq[0]++;
            }
            else {
 
                // Otherwise, increment count
                // of subarrays with odd XOR
                ans += freq[1];
                freq[1]++;
            }
        }
 
        // Print the result
        System.out.println(ans);
    }
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // Given array
        int arr[] = { 1, 2, 3, 4 };
 
        // Stores the size of the array
        int N = arr.length;
 
        evenXorSubarray(arr, N);
    }
}

Python3

# Python3 program for the above approach
 
# Function to count subarrays
# having even Bitwise XOR
def evenXorSubarray(arr, n):
     
    # Store the required result
    ans = 0
 
    # Stores count of subarrays
    # with even and odd XOR values
    freq = [0] * n
 
    # Stores Bitwise XOR of
    # current subarray
    XOR = 0
 
    # Traverse the array
    for i in range(n):
 
        # Update current Xor
        XOR = XOR ^ arr[i]
 
        # If XOR is even
        if (XOR % 2 == 0):
 
            # Update ans
            ans += freq[0] + 1
 
            # Increment count of
            # subarrays with even XOR
            freq[0] += 1
         
        else:
 
            # Otherwise, increment count
            # of subarrays with odd XOR
            ans += freq[1]
            freq[1] += 1
         
    # Print the result
    print(ans)
 
# Driver Code
 
# Given array
arr = [ 1, 2, 3, 4 ]
 
# Stores the size of the array
N = len(arr)
 
evenXorSubarray(arr, N)
 
# This code is contributed by sanjoy_62

C#

// C# program for the above approach
using System;
class GFG
{
  // Function to count subarrays
  // having even Bitwise XOR
  static void evenXorSubarray(int[] arr, int n)
  {
     
    // Store the required result
    int ans = 0;
 
    // Stores count of subarrays
    // with even and odd XOR values
    int[] freq = { 0, 0 };
 
    // Stores Bitwise XOR of
    // current subarray
    int XOR = 0;
 
    // Traverse the array
    for (int i = 0; i < n; i++) {
 
      // Update current Xor
      XOR = XOR ^ arr[i];
 
      // If XOR is even
      if (XOR % 2 == 0) {
 
        // Update ans
        ans += freq[0] + 1;
 
        // Increment count of
        // subarrays with even XOR
        freq[0]++;
      }
      else {
 
        // Otherwise, increment count
        // of subarrays with odd XOR
        ans += freq[1];
        freq[1]++;
      }
    }
 
    // Print the result
    Console.WriteLine(ans);
  }
 
 
  // Driver Code
  public static void Main(String[] args)
  {
    // Given array
    int[] arr = { 1, 2, 3, 4 };
 
    // Stores the size of the array
    int N = arr.Length;
 
    evenXorSubarray(arr, N);
  }
}
 
// This code is contributed by susmitakundugoaldanga.

Java脚本


输出:
4

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