📜  计算具有偶数位异或的子数组

📅  最后修改于: 2021-10-26 06:24:06             🧑  作者: Mango

给定一个大小为N的数组arr[] ,任务是计算给定数组中按位异或为偶数的子数组的数量。

例子:

朴素的方法:解决这个问题的最简单的方法是生成所有可能的子数组并检查每个子数组的所有元素的按位异或是否为偶数。如果发现是偶数,则增加计数。最后,打印计数作为结果。

下面是上述方法的实现:

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] 与其他具有偶数异或值的子数组进行异或运算时,会产生偶数异或值。此外,添加 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);
    }
}

蟒蛇3

# 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)
辅助空间: O(1)

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