Luffy_18's blog

By Luffy_18, history, 30 hours ago, In English

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!

  • Vote: I like it
  • +1
  • Vote: I do not like it

»
25 hours ago, # |
  Vote: I like it 0 Vote: I do not like it

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 of set 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.

  • »
    »
    21 hour(s) ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    I already tried unordered_map, unordered_set, vector. But they also are ending up with TLE :(

    • »
      »
      »
      14 hours ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      maybe use map?

      • »
        »
        »
        »
        5 hours ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        :) not worked either

»
3 hours ago, # |
  Vote: I like it 0 Vote: I do not like it

Check the constraints. The input A[i] is upto 1e17 but you have initialized vector. That may result in negative numbers and TLE.