Hi everyone, I'm working on a problem from AtCoder, and I need some help optimizing my current solution. Here's the link to the problem: LINK
My current approach: I tried solving this using recursion. I am exploring all possible states/stages, but it results in TLE even for ( n = 12 ). I believe this might be because the complexity grows very quickly, possibly factorial.
My code:
#include <iostream>
#include<vector>
#include<set>
using namespace std;
#define int long long
#define vi vector<int>
set<int> st;
int CalcXor(vi &a){
int res = 0;
for(auto i : a){
res ^= i;
}
return res;
}
void f(vi &a, int n, int currXOR){
if(n == 0){
st.insert(currXOR);
return;
}
int nums = a[n - 1];
currXOR ^= nums;
a[n - 1] = 0;
for (int i = 0; i < n; ++i) {
currXOR ^= a[i];
a[i] += nums;
currXOR ^= a[i];
f(a, n - 1, currXOR);
currXOR ^= a[i];
a[i] -= nums;
currXOR ^= a[i];
}
currXOR ^= nums;
a[n - 1] = nums;
}
void solve() {
int n; cin >> n;
vi a(n);
for (int i = 0; i < n; ++i) {
cin >> a[i];
}
vi temp = a;
int _xor = CalcXor(a);
f(a, n, _xor);
cout << st.size();
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
solve();
return 0;
}
It would be a great help if anyone could guide me through this. Thanks in advance for your help!