6

A Beautiful Technique for Some XOR Related Problems

 1 year ago
source link: https://codeforces.com/blog/entry/68953?f0a28=1
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Inspiration

I'm very excited about this blog, as it took me quite a lot of effort and scavenging through the internet to completely grasp the concept of this technique(That's probably because I have almost zero knowledge in Linear Algebra or I'm just plain dumb). So I feel like I genuinely conquered a challenge, and I really want to share it with someone. But there's no way my CP friends circle will believe it, they'll think I'm just trying to show off :P

So here I am, sharing it on CF. I also created a personal blog, so that if I ever feel like sharing something again(not only about CP), I can write a blog there. I also added this same post there, you can read it there if you prefer dark theme. I'll be pleased to hear any thoughts on the blog or if I can improve it in some way ^_^

Introduction

Since it concerns Linear Algebra, there needs to be a lot of formal stuff going on in the background. But, I'm too much inconfident on this subject to dare go much deep. So, whenever possible, I'll try to explain everything in intuitive and plain English words. Also, this blog might take a while to be read through completely, as there are quite a few observations to grasp, and the example problems aren't that easy either. So please be patient and try to go through it all, in several sits if needed. I believe it'll be worth the time. In any case, I've written the solutions, codes, and provided links to their editorials(if available). I'll provide more details in the solutions tomorrow and put more comments in the codes, since I'm really tired from writing this blog all day.

Now, the problems that can be solved using this technique are actually not much hard to identify. The most common scenario involves: you'll be given an array of numbers, and then the problem asks for an answer by considering all the xor-sums of the numbers in all possible subsets of the array. This technique can also be used in some online-query problems: the problem can provide queries of first type instructing you to insert numbers in the array(_without removal_, I don't know how to solve with deletion of elements) and in-between those queries, asking for answers in separate queries of second type.

The whole technique can be divided into two main parts, some problems can even be solved by using only the first part(Don't worry if you don't understand them completely now, I explain them in details right below): 1. Represent each given number in it's binary form and consider it as a vector in the vector space, where is the maximum possible number of bits. Then, xor of some of these numbers is equivalent to addition of the corresponding vectors in the vector space. 2. Somehow, relate the answer to the queries of second type with the basis of the vectors found in Part 1.

PS: Does anyone know any name for this technique? I'm feeling awkward referring to it as 'technique' this many times :P If it's not named yet, how about we name it something?

Part 1: Relating XOR with Vector Addition in

Let me explain the idea in plain English first, then we'll see what the and vector space means. I'm sure most of you have already made this observation by yourselves at some point.

Suppose, we're xor-ing the two numbers and Let's do it below:

Now, for each corresponding pair of bits in the two numbers, compare the result of their xor with the result of their sum taken modulo :

Bit no. First number Second number Sum Sum taken
st bit
nd bit

Notice the similarity between columns and ? So, we can see that taking xor between two numbers is essentially the same as, for each bit positions separately, taking the sum of the two corresponding bits in the two numbers modulo

Now, consider a cartesian plane with integer coordinates, where the coordinate values can only be or If any of the coordinates, exceeds or goes below we simply take it's value modulo

This way, there can only be points in this plane: Writing any other pair of coordinates will refer to one of them in the end, for example, point is the same point as point since and modulo

In view of this plane, we can represent the number as the point by setting the first bit of as the coordinate and the second bit as the coordinate in our plane. Refer to this point as Then, the position vector of will be where is the origin. Similarly, the position vector of will be where

An interesting thing happens here, if we add the two position vectors, the corresponding coordinates get added modulo which actually gives us the position vector of the xor of these two position vectors. For example, adding vectors and we get where turns out to be the point corresponding the xor of and

This is all there is to it. Transforming xor operations to bitwise addition modulo and, in some cases, vector addition in this way can be helpful in some problems. Let's see one such problem. Before that, let me explain in short what vector space and meant earlier. I apologize to any Linear Algebra fans, since I don't want to write formal definitions here to make things look harder than it is. I'll explain the idea of these terms the way I find them in my mind, kindly pardon me for any mistakes and correct me if I'm wrong.

: Just a collection of vectors.

: is the set of remainders upon division by So, is simply the set since these are the only remainders possible when taken modulo

: A dimensional vector space consisting of all the different position vectors that consists of coordinates, all coordinates being elements of For example, earlier our custom cartesian plane was a two-dimensional one. So, it was would be a small plane with only points, all coordinates taken modulo

So, what we've seen is that the xor-operation is equivalent to vector addition in a vector space. See how unnecessarily intimidating this simple idea sounds when written in formal math!

Anyways, the problem:

Problem 1 (Division 2 — C)


Find the number of non-empty subsets, modulo of a given set of size with range of elements such that the product of it's elements is a square number.
Link to the source

If you'd like to solve the problem first, then kindly pause and try it before reading on further.

Solution

Since the number of different possible masks were just in the previous problem, we had been able to use dynamic programming for checking all possible xors. But what if the constraint was much bigger, say That is when we can use Part of this technique, which, in some cases, works even when the queries are online.

Part 2: Bringing in Vector Basis

We need a couple of definitions now to move forward. All the vectors mentioned in what follows, exclude null vectors. I sincerely apologize for being so informal with these definitions.

A set of vectors is called independent, if none of them can be written as the sum of a linear combination of the rest.

A set of vectors is called a basis of a vector space, if all of the element vectors of that space can be written uniquely as the sum of a linear combination of elements of that basis.

A few important properties of independent vectors and vector basis that we will need later on(I find these pretty intuitive, so I didn't bother with reading any formal proofs. Let me know in the comments if you need any help):

  1. For a set of independent vectors, we can change any of these vectors by adding to it any linear combination of all of them, and the vectors will still stay independent. What's more fascinating is that, the set of vectors in the space representable by some linear combination of this independent set stays exactly the same after the change.

  2. Notice that, in case of vector space, the coefficients in the linear combination of vectors must also lie in Which means that, an element vector can either stay or not stay in a linear combination, there's no in-between.

  3. The basis is actually the smallest sized set such that all other vectors in the vector space are representable by a linear combination of just the element vectors of that set.

  4. The basis vectors are independent.

  5. For any set with smaller number of independent vectors than the basis, not all of the vectors in the space will be representable.

  6. And there cannot possibly be larger number of independent vectors than basis in a set. If is the size of the basis of a vector space, then the moment you have independent vectors in a set, it becomes a basis. You cannot add another vector into it, since that new vector is actually representable using the basis.

  7. For a dimensional vector space, it's basis can have at most vector elements.

With just these few properties, we can experience some awesome solutions to a few hard problems. But first, we need to see how we can efficiently find the basis of a vector space of vectors, where each vector is an element of The algorithm is quite awesome <3 And it works in

The Algorithm:


This algorithm extensively uses properties and and also the rest in the background. All the vectors here belong to so they are representable by a bitmask of length
Suppose at each step, we're taking an input vector and we already have a basis of the previously taken vectors and now we need to update the basis such that it can also represent the new vector
In order to do that, we first need to check whether is representable using our current basis or not.
If it is, then this basis is still enough and we don't need to do anything. But if it's not, then we just add this vector to the set of basis.
So the only difficuly that remains is, to efficiently check whether the new vector is representable by the basis or not. In order to facilitate this purpose, we use property to slightly modify any new vectors before inserting it in the basis, being careful not to break down the basis. This way, we can have more control over the form of our basis vectors. So here's the plan:
Let, be the first position in the vector's binary representation, where the bit is set. We make sure that all the basis vectors each have a different value.
Here's how we do it. Initially, there are no vectors in the basis, so we're fine, there are no values to collide with each other. Now, suppose we're at the 'th step, and we're checking if vector is representable by the basis or not. Since, all of our basis have a different value, take the one with the least value among them, let's call this basis vector
If then no matter how we take the linear combination, by property no linear combination of the basis vectors' can have at position So, will be a new basis vector, and since it's value is already different from the rest of the basis vectors, we can insert it into the set as it is and keep a record of it's value.
But, if then we must subtract from if we want to represent as a linear combination of the basis vectors, since no other basis vector has bit at position So, we subtract from and move on to
Note that, by changing the value of we're not causing any problem according to property and is of same use to us. If in some later step we find out is actually not representable by the current basis, we can still just insert it's changed value in the basis, since the set of vectors in the space representable by this new basis would've been the same if we inserted the original instead.
If, after iterating through all the basis vector 's and subtracting them from if needed, we still find out that is not null vector, it means that the new changed has a larger value of than all other basis vectors. So we have to insert it into the basis and keep a record of it's value.

Here's the implementation, the vectors being represented by bitmasks of length :

int basis[d]; // basis[i] keeps the mask of the vector whose f value is i

int sz; // Current size of the basis

void insertVector(int mask) {
	for (int i = 0; i < d; i++) {
		if ((mask & 1 << i) == 0) continue; // continue if i != f(mask)

		if (!basis[i]) { // If there is no basis vector with the i'th bit set, then insert this vector into the basis
			basis[i] = mask;
			++sz;
			
			return;
		}

		mask ^= basis[i]; // Otherwise subtract the basis vector from this vector
	}
}

Let's view some problems now:

Problem 2a


Given a set of size with elements Find the number of distinct integers that can be represented using xor over the set of the given elements.
Link to the source

Solution

Problem 2b


We have a graph of nodes numbered from to Also, we're given integers within the range In the graph, two vertices and are connected with an edge iff for some Find the number of connected components in the graph.
Link to the source
Link to the editorial and reference code


Problem 3


Given a set of size with elements What is the maximum possible xor of the elements of some subset of
Link to the source

Solution

Problem 4 (1st Hunger Games — S)


We have an empty set and we are to do queries on it. Let, denote the set of all possible xor-sums of elements from a subset of There are two types of queries.
Type : Insert an element to the set(If it's already in the set, do nothing)
Type : Given print the 'th hightest number from It's guaranteed that Link to the source

Solution

Problem 5 (Division 2 — F)


You're given an array of length You have to answer queries.
In each query you'll be given two integers and Find the number of subsequences of the first elements of this array, modulo such that their bitwise-xor sum is
Link to the source

Solution

Problem 6 (Education Round — G)


You are given an array of integers. You have to find the maximum number of segments this array can be partitioned into, such that -
1. Each element is contained in exactly one segment
2. Each segment contains at least one element
3. There doesn't exist a non-empty subset of segments such that bitwise-xor of the numbers from them is equal to
Print if no suitable partition exists.
Link to the source

Solution

Conclusion

This is my first take on writing tutorial blogs on CF. I hope it'll be of use to the community.

I apologize for my terrible Linear Algebra knowledge. I would write this blog without using any of it if I could. I don't want to spread any misinformation. So please let me know in comments if you find any mistakes/wrong usage of notations.

I plan to write on Hungarian Algorithm next. There's just so many prerequisites to this algorithm. It'll be an enjoyable challenge to write about. I'd be glad if you can provide me some resource links in the comments to learn it from, though I already have quite a few.

References:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK