Skip to content

Commit dff31cb

Browse files
authored
Merge pull request #480 from ishikasinha-d/master
Maximum Subset XOR in cpp
2 parents 9345c60 + 23d301e commit dff31cb

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

Bit Manipulation/max_subset_XOR.cpp

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// Given an array of N positive integers. Find an integer denoting the maximum XOR subset value in the given array.
2+
// Time complexity: O(n)
3+
4+
5+
#include<bits/stdc++.h>
6+
#define fl(i,a,b) for(i=a;i<b;i++)
7+
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
8+
using namespace std;
9+
typedef long long int ll;
10+
11+
ll maxSubsetXOR(ll set[], ll n)
12+
{
13+
ll index=0, max_pos, max;
14+
for (ll i = 31; i >= 0; i--)
15+
{
16+
max= LONG_MIN;
17+
max_pos= index;
18+
for (ll j = index; j < n; j++)
19+
{
20+
if ( (arr[j] & (1 << i)) != 0 && arr[j] > max )
21+
{
22+
max= arr[j];
23+
max_pos= j;
24+
}
25+
26+
}
27+
if (max == LONG_MIN)
28+
continue;
29+
30+
swap(arr[index], arr[max_pos]);
31+
max_pos = index;
32+
33+
for (ll j=0; j<n; j++)
34+
{
35+
if (j != max_pos && (arr[j] & (1 << i)) != 0)
36+
arr[j] = arr[j] ^ arr[max_pos];
37+
}
38+
index++;
39+
}
40+
ll ans = 0;
41+
for (ll i = 0; i < n; i++)
42+
ans ^= arr[i];
43+
return ans;
44+
}
45+
46+
int main()
47+
{
48+
fast;
49+
50+
#ifndef ONLINE_JUDGE
51+
freopen("input.txt","r",stdin);
52+
freopen("output.txt","w",stdout);
53+
#endif
54+
55+
ll n; cin>>n;
56+
ll arr[n];
57+
for(auto &x: arr)
58+
cin>>x;
59+
60+
cout << maxSubsetXOR(arr, n);
61+
62+
return 0;
63+
64+
}

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ This repository contains all the popular Competitive Programming questions and I
2424
<li><a href="https://github.com/smv1999/CompetitiveProgrammingQuestionBank/tree/master/General%20Questions">General Questions</a></li>
2525
<li><a href="https://github.com/smv1999/CompetitiveProgrammingQuestionBank/tree/master/Greedy">Greedy</a></li>
2626
<li><a href="https://github.com/smv1999/CompetitiveProgrammingQuestionBank/tree/master/Hackerrank%20solutions">HackerRank Solutions</a></li>
27+
<li><a href="https://github.com/smv1999/CompetitiveProgrammingQuestionBank/tree/master/Hashing">Hashing</a></li>
2728
<li><a href="https://github.com/smv1999/CompetitiveProgrammingQuestionBank/tree/master/Numbers">Numbers</a></li>
2829
<li><a href="https://github.com/smv1999/CompetitiveProgrammingQuestionBank/tree/master/OOPs">OOPs</a></li>
2930
<li><a href="https://github.com/smv1999/CompetitiveProgrammingQuestionBank/tree/master/Passwords">Passwords</a></li>

0 commit comments

Comments
 (0)