-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathbennybits.cpp
47 lines (39 loc) · 1.23 KB
/
bennybits.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include<bits/stdc++.h>
using namespace std;
// Returns count of subsets of arr[] with XOR value equals
// to k.
int subsetXOR(int arr[], int n, int k)
{
// Find maximum element in arr[]
int max_ele = arr[0];
for (int i=1; i<n; i++)
if (arr[i] > max_ele)
max_ele = arr[i];
// Maximum possible XOR value
int m = (1 << (int)(log2(max_ele) + 1) ) - 1;
// The value of dp[i][j] is the number of subsets having
// XOR of their elements as j from the set arr[0...i-1]
int dp[n+1][m+1];
// Initializing all the values of dp[i][j] as 0
for (int i=0; i<=n; i++)
for (int j=0; j<=m; j++)
dp[i][j] = 0;
// The xor of empty subset is 0
dp[0][0] = 1;
// Fill the dp table
for (int i=1; i<=n; i++)
for (int j=0; j<=m; j++)
dp[i][j] = dp[i-1][j] + dp[i-1][j^arr[i-1]];
// The answer is the number of subset from set
// arr[0..n-1] having XOR of elements as k
return dp[n][k];
}
// Driver program to test above function
int main()
{
int arr[] = {1, 2, 3, 4, 5};
int k = 4;
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Count of subsets is " << subsetXOR(arr, n, k);
return 0;
}