



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




FIND MEMBERS
JOIN LOG IN
DESIGN CHALLENGES
DEVELOPMENT CHALLENGES
DATA SCIENCE CHALLENGES
COMPETITIVE PROGRAMMING
GETTING STARTED
DESIGN
DEVELOPMENT
DATA SCIENCE
COMPETITIVE PROGRAMMING
OVERVIEW
PROGRAMS
FORUMS
STATISTICS
EVENTS
BLOG
By bmerry– TopCoder Member Discuss this article in the forums
Introduction Most of the optimizations that go into TopCoder challenges are high-level; that is, they affect the algorithm rather than the implementation. However, one of the most useful and effective low-level optimizations is bit manipulation, or using the bits of an integer to represent a set. Not only does it produce an order-of-magnitude improvement in both speed and size, it can often simplify code at the same time.
I’ll start by briefly recapping the basics, before going on to cover more advanced techniques.
The basics At the heart of bit manipulation are the bit-wise operators & (and), | (or), ~ (not) and ^ (xor). The first three you should already be familiar with in their boolean forms (&&, || and !). As a reminder, here are the truth tables:
The bit-wise versions of the operations are the same, except that instead of interpreting their arguments as true or false, they operate on each bit of the arguments. Thus, if A is 1010 and B is 1100, then
~A = 11110101 (the number of 1′s depends on the type of A).
Finally, there is a portable method that performs well in cases where the looping solution would require many iterations. Use each byte of the 4- or 8-byte integer to index a precomputed 256-entry table that stores the index of the highest (lowest) set bit in that byte. The highest (lowest) bit of the integer is then the maximum (minimum) of the table entries. This method is only mentioned for completeness, and the performance gain is unlikely to justify its use in a TopCoder match.
Counting out the bits One can easily check if a number is a power of 2: clear the lowest 1 bit (see above) and check if the result is 0. However, sometimes it is necessary to know how many bits are set, and this is more difficult.
GCC has a function called __builtin_popcount which does precisely this. However, unlike __builtin_ctz, it does not translate into a hardware instruction (at least on x86). Instead, it uses a table-based method similar to the one described above for bit searches. It is nevertheless quite efficient and also extremely convenient.
Users of other languages do not have this option (although they could re-implement it). If a number is expected to have very few 1 bits, an alternative is to repeatedly extract the lowest 1 bit and clear it.
All the subsets A big advantage of bit manipulation is that it is trivial to iterate over all the subsets of an N-element set: every N-bit value represents some subset. Even better, if A is a subset of B then the number representing A is less than that representing B, which is convenient for some dynamic programming solutions.
It is also possible to iterate over all the subsets of a particular subset (represented by a bit pattern), provided that you don’t mind visiting them in reverse order (if this is problematic, put them in a list as they’re generated, then walk the list backwards). The trick is similar to that for finding the lowest bit in a number. If we subtract 1 from a subset, then the lowest set element is cleared, and every lower element is set. However, we only want to set those lower elements that are in the superset. So the iteration step is just i = (i ‐ 1) & superset.
Even a bit wrong scores zero There are a few mistakes that are very easy to make when performing bit manipulations. Watch out for them in your code.
will shift in zeros.
Cute tricks There are a few other tricks that can be done with bit manipulation. They’re good for amazing your friends, but generally not worth the effect to use in practice. Reversing the bits in an integer
x = ((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1); x = ((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2); x = ((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4); x = ((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8); x = ((x & 0xffff0000) >> 16) | ((x & 0x0000ffff) << 16);
As an exercise, see if you can adapt this to count the number of bits in a word. Iterate through all k-element subsets of {0, 1, … N-1}
int s = (1 << k) ‐ 1; while (!(s & 1 << N)) { // do stuff with s int lo = s & ~(s ‐ 1); // lowest one bit int lz = (s + lo) & ~s; // lowest zero bit above lo s |= lz; // add lz to the set s &= ~(lz ‐ 1); // reset bits below lz s |= (lz / lo / 2) ‐ 1; // put back right number of bits at end }
In C, the last line can be written as s |= (lz >> ffs(lo)) ‐ 1 to avoid the division. Evaluate x? y : ‐y, where x is 0 or 1
(‐x ^ y) + x
This works on a twos-complement architecture (which is almost any machine you find today), where negation is done by inverting all the bits then adding 1. Note that on i686 and above, the original expression can be evaluated just as efficiently (i.e., without branches) due to the CMOVE (conditional move) instruction.
Sample problems TCCC 2006, Round 1B Medium For each city, keep a bit-set of the neighbouring cities. Once the part-building factories have been chosen (recursively), ANDing together these bit-sets will give a bit-set which describes the possible locations of the part-
© 2015 Topcoder. All Rights Reserved
SITEMAP
ABOUT US
CONTACT US
HELP CENTER
PRIVACY POLICY
TERMS
Topcoder is also on
if (i & (i << 1)) continue; pg.push_back(i); pgb.push_back(__builtin_popcount(i)); }
Member Tutorials Read more than 40 data science tutorials written by topcoder members.
Problem Set Analysis Read editorials explaining the problem and solution for each Single Round Match (SRM).
Data Science Guide New to topcoder's data science track? Read this guide for an overview on how to get started in the arena and how competitions work.
Help Center Need specifics about the process or the rules? Everything you need to know about competing at topcoder can be found in the Help Center.
Member Forums Join your peers in our member forums and ask questions from the real experts - topcoder members!
More Resources