Editorial
Let . Every input value is smaller than , so considering bits through is sufficient.
For and , put every index satisfying into a node . Bits are read from least significant to most significant. Thus, the two children of are and .
Index gives the following demand to node :
Suppose a composition of additions and XORs maps an input value to . The lower bits of depend only on the lower bits of . Therefore, all demands assigned to one node must be equal.
The following lemma is the key observation.
Lemma. Write for the change of bit at node . These changes can be produced by a composition of additions and XORs if and only if, for every , the following value is the same for every :
There is only one node at , so no separate condition is needed there. The lemma can be proved by checking the identity for an addition and an XOR, then constructing a composition bit by bit from lower bits to higher bits. The additional bit prevents a wraparound that would only be valid modulo a power of two. The nonnegativity restriction can be met by using a sufficiently large common offset during the construction.
Call a node containing at least one index an active node. If one active node receives different demands, the transformation is impossible. Otherwise, denote its common demand by .
If both children of an active node are active, the value in the lemma is forced to be
If one child is empty, its value is free and creates no restriction. Consequently, a transformation exists if and only if both conditions below hold.
- All demands agree inside every active node.
- At each depth , all nodes with two active children have the same value of .
Maintain a binary trie of the values in , inserting bits from least significant to most significant. Each node stores the number of indices demanding and the number demanding . We also maintain the total number of nodes with conflicting demands and, at every depth, the numbers of branching nodes forcing each of the two possible values of .
When one element changes, remove the old pair from the trie and insert the new pair. Only one root-to-leaf path is affected. The status of a node can be updated using that node and its two children.
The time complexity of one query is , and the total space complexity is .
Solution written by GPT5