fork download
  1. // A simple C++ Program to count all subarrays having
  2. // XOR of elements as given value m
  3. #include <bits/stdc++.h>
  4. using namespace std;
  5.  
  6. // Simple function that returns count of subarrays
  7. // of arr with XOR value equals to m
  8. long long subarrayXor(int arr[], int n, int l,int r)
  9. {
  10. long long ans = 0; // Initialize ans
  11.  
  12. // Pick starting point i of subarrays
  13. for (int i = l-1; i < r; i++) {
  14. int xorSum = 0; // Store XOR of current subarray
  15.  
  16. // Pick ending point j of subarray for each i
  17. for (int j = i; j < r; j++) {
  18. // calculate xorSum
  19. xorSum = xorSum ^ arr[j];
  20.  
  21. // If xorSum is equal to given value,
  22. // increase ans by 1.
  23. if (xorSum + 1 ==xorSum^1 )
  24. ans++;
  25. }
  26. }
  27. return ans;
  28. }
  29.  
  30. // Driver program to test above function
  31. int main()
  32. {
  33. int arr[] = { 1, 2, 9, 8, 7 };
  34. int n = sizeof(arr) / sizeof(arr[0]);
  35. int m = 6;
  36.  
  37. int l=1;
  38. int r=5;
  39.  
  40. cout << "Number of subarrays having given XOR is "
  41. << subarrayXor(arr, n, l,r);
  42. return 0;
  43. }
  44.  
Success #stdin #stdout 0.01s 5448KB
stdin
Standard input is empty
stdout
Number of subarrays having given XOR is 15