Algorithm to add sum of every possible xor-sum sub-array

后端 未结 3 857
小蘑菇
小蘑菇 2021-02-06 13:36

I participated in one algorithmic competition. I got stuck in one problem, I am asking the same here.

Problem Statement

XOR-sum array is to XOR

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-06 14:03

    Think of the numbers arranged in a Nx32 matrix, where each row represents a number in array and each column represents i'th bits of all the numbers. Now, effects of XOR operation are confined within a column. Therefore, we can separate each column, calculate the XOR-sum for that column and add it to the result.

    I have separated a column. How to calculate XOR-sum within this column?

    For this purpose, we count the number of 1 in this column. Let c denote the number of 1 in a column. Then, number of 0 will be N - c. To produce 1 in column result (0s have no effect on final result), for each 1 from c, we can take a 0 from N - c, or take no 0 at all. Therefore, there are N - c + 1 ways for each 1 to produce 1 after XOR operation. As there are c 1s, Total number of 1 after XOR operation is c * (N - c + 1).

    Each column contributes differently to the final result with respect to there position i. Therefore, multiply column-result with 2^i (1 << i) and add this to final result.

    • for (int i=0, p=1; i<30; i++, p<<=1)
      This loop separates the columns. It also makes p = 1 << i.
    • if (A[j]&p) c++;
      This line counts number of 1 in a column.
    • ret+=(long long)c*(N-c+1)*p;
      This elevates the column-result with respect to column position and add this to final result. Remember that, p = 1 << i (= 2^i).

    CONFESSION: I only explained what is done in the code. I have no proof that this will cover all the sub-arrays.

提交回复
热议问题