G - Xor Cards Editorial by LFCode


  • Lemma 1 we will choose at most \(O(\log V)\) cards, for they are enough to express all the values we need. This can be proved by Linear Basis Theory.
  • Lemma 2 Consider two cards \((a,b)\) and \((c,d)\). There’s a fact thar the answer will not change if we replace \((c,d)\) with \((c\oplus a,d\oplus b)\).

Now let’s consider a card \((a,b)\), which \(a\) can be linear expressed by other cards. We can repeatly let \(a=a\oplus a'\) until \(a=0\) and do the similar change to \(b\) (that means, let \(b=b\oplus b'\) at the same time). After that, we can get a pair \((0,c)\). According to Lemma 1 , it is completely equal to the original pair \((a,b)\), so we can always find a way to use the number \(c\) without doing any change to the “exclusive logical sum” of \(A\) on the chosen cards.

After the analysis, it’s not hard to come up with a method to construct a pair of Linear Basis: try to insert all the \(A\) to a basis \(L_1\) and record the corresponding \(B\). If the number \(A\) we tried to insert can be linear expressed, then insert the rest number of \(B\) after elimination to the other basis \(L_2\).

Now we can express all the methods of choosing cards using these two Linear Basis.

The next work is to consider the limit of \(K\). Let’s think about two easier problems first.


Problem 1 If the “exclusive logical sum” of \(A\) chosen is given(for example, let it be \(S\)), how to construct a method using elements in \(L_1\)?

This is a classical problem. The method of linear expressing \(S\) using numbers in \(L_1\) is unique. Just check all the bits one by one.

Problem 2 How to choose some elements from \(L_2\) in order to maximum the “exclusive logical sum” of all of them and a given number \(X\)?

This problem is also classical. There is a greedy method: check the bits from high to low and check if the value will be better after choosing the element on that bit.


Now all the preparations are finished. We can check all the bits which exists in \(K\), force the “exclusive logical sum” of \(A\) chosen to be the same as \(K\) on higher bits, and different to \(K\) on that bit.

Now, we can notice that the way to express higher bits is unique (just like Problem 1 above), and we can arbitrarily choose elements in lower bits (because the sum is different to \(K\) on current bit, it won’t be bigger than \(K\)). How to construct the best method? That is just Problem 2 ! Just insert the elements with lower bits in \(L_1\) and all the elements in \(L_2\) into a new basis and solve Problem 2 .

Now the problem has been solved. The time complexity of the algorithm is \(O(n\log V+\log^3V)\).

My Code

Sorry for my poor English. If you think my expression is not clear, you can send me message on Codeforces.

posted:
last update: