Understanding the Editorial for Prime XOR - HackerRank

Viewed 4102

Disclaimer: This question involves content from the corresponding editorial. Thus, if you want to attempt this problem on your own, I discourage you from reading this post. Also, my question leaves out some details mentioned in the editorial, so please do refer to the editorial as you read my question.

Also, please bear in my mind that it is not my intention to advertise for HackerRank; furthermore, in no way, am I taking credit for the content on the editorial, problem description, or any other material that would be deemed a copyright infringement by HackerRank or affiliated parties).


Actual Question:

I'm trying to understand the editorial for this problem. Specifically, the part that I'm getting confused over is the following piece of code:

...
for(int i=1;i<=k;i++) {
    for(int j=0;j<8192;j++) {
        mem[flag][j] = (mem[flag^1][j]*(1+(a[v[i-1]])/2))%mod + (mem[flag^1][j^v[i-1]]*((a[v[i-1]]+1)/2))%mod;
        if(mem[flag][j]>=mod)
            mem[flag][j]%=mod;
    }
    flag = flag^1;
}

The editorial states that "...Using this property, we can write a O(N) dynammic programming solution with 8192 constant factor such that dp[i][j] would store the count of subsets that can be formed with the first elements such that the xor-sum of the elements in the subset is j."

From the code, it appears that mem is essentially dp, except I can't wrap my head around the function of flag -- what is flag?. Also, I get that 1 + (a[v[i - 1]])/2 corresponds with the number of evens in [0, a[v[i - 1]]] and (a[v[i - 1]] + 1) / 2corresponds with the number of odds in that same interval, but I don't see how it quite ties in with everything.

Thanks in advance for your efforts.

2 Answers

flag is used to reduce excess use of memory since dp is dependent upon previous state only .

why loop [0,8192] : As it is given in the question that a[i]<=4500 then when we xor two number it will reach upto 8192 . Xor property ..

Related