Finding the No. of Subset with a Given Xor

旧街凉风 提交于 2019-12-10 15:18:17

问题


I have an array with 10^5 elements where each element is in [0, 1023]. I have to find the number of subsets of an array such that XOR of element is Q. (for Q>1023 the answer is 0). I came up with this O(N*1024) Approach

for (int i = 1; i <= n; i++ )
{
    int a = F[i]; 
    for (int j = 0; j < 1024; j++ )
    {
        ways[i][j] = ways[i-1][j] + ways[i-1][j^a];
        if (ways[i][j] >= mod) 
            ways[i][j] -= mod;
    }
}

Since elements are in Range up to 1023 , could i maintain an array of Frequency F[i] , reduce the above code upto O(1024*1024). Is this possible ,can Frequency array could be useful ?


回答1:


Well, the answer is almost always 2^(N-10)

First, note that if you XOR one element into another, it doesn't change the number of subsets that XOR to Q.

Proof of that: Lets say that you have your array A of size N, and a bunch of subsets that XOR to particular values. Then you do A[i] ^= A[j], with i!=j. Now, to fix all the subsets so that they XOR to the same values, you just find the ones that include A[i], and toggle A[j] in them. So the XOR we did doesn't affect the total number of subsets that XOR to any particular value.

So...

  1. Find the largest element and move it into position 0. Then XOR it into all the other elements that have the same MSB (most significant bit), so that A[0] is the only element with the largest MSB.

  2. Find the largest remaining element, moving it to position 1, and XOR it into all the remaining elements with the same MSB, so A[1] will be the only element with the second-largest MSB.

  3. Continue with the 3rd largest MSB, etc., as many times as you can. You end up with at most 10 non-zero elements, all with different MSBs, and the remaining elements will all be zero.

Lets say you end up with M non-zero elements. If you can make Q by XORing these elements together, then there will only be one way to do it. The other N-M elements are all zero, so you can add or remove them from any subset without changing the total XOR value. So if you can make Q then there will be 2^(N-M) subsets that XOR to Q.

If you can't make Q by XORing those non-zero elements, then of course the number of subsets that XOR to Q is 0.

For more information on this procedure, google "Gaussian Elimination"



来源:https://stackoverflow.com/questions/34136955/finding-the-no-of-subset-with-a-given-xor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!