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!
The complexity is the number of partitions which is Bell's number. In this problem
Unable to parse markup [type=CF_MATHJAX]
If you use
unordered_map
instead ofset
you would get accepted.Note that if you just read the blog it would be enough and you don't need to wait for an answer.
I already tried unordered_map, unordered_set, vector. But they also are ending up with TLE :(
maybe use map?
:) not worked either
Check the constraints. The input A[i] is upto 1e17 but you have initialized vector. That may result in negative numbers and TLE.