Bit operations: ACM optimized application

Source: Internet
Author: User
Source http://hi.baidu.com/zfy0701/blog/item/6bd496894a77aeb60f244422.html#send
Article organization:
1. Basic Operators
2. Notes
3. Some small applications
4. Application of specific questions
1> Search
2> string type
3> other classes

Basic Operators
And &
Or |
Exclusive or ^
Left and right shift </>
Reverse retrieval ~

Notes:
1. priority. This is a very serious problem. The priority is too easy to ignore during bit operations.
Note:
Shift Operator, single-objective Inverse Operator ~ The priority is higher than the comparison operator. However, &, |, ^ has a lower priority than comparison operators !, Pay attention to this.
For example, the result of 6 & 6> 4 is 0, rather than true; (6 & 6)> 4 is true, so remember to add brackets

2. Speed
Bit operations are very fast. You can even ignore the time consumed by bit operations, but after all, operations are definitely consumable.
Therefore, try to use
^ =, | =, & = And other operations, such as a ^ = B, are faster than a = a ^ B because the former is directly performed on, the second A of A = a ^ B is a copy of a. It can be seen that in the operation, the program copies A, and the result of the Operation assigns a value to.

3. Range (beware of a range overflow during shift operations)

Common Operations:
1. Exchange the values of two elements: a ^ = B ^ = a ^ = B. You do not need to use the third variable.

2. Do not look up the number of statistical items 1
Int bitcnt (unsigned int N ){
Int value = 0;
While (n) ++ value, N & = n-1;
Return value;
}

3. Cyclic Displacement
Unsigned shift (unsigned now, int N, int N) {// n indicates moving left; otherwise, it indicates moving right.
If (n> 0)
Now = (now> (n-n) | (now <n );
If (n <0 ){
N =-N;
Now = (now <(n-n) | (now> N );
}
Now & = base;
Return now;
}

4. K-bit Inversion
A = ~ (~ A ^ (A <k ))

Advantages:
Fast,
Saves space and leads to high speed.

Poj questions:

Category 1: Search
Here we will not discuss the question, but how bitwise operations are implemented and applied in these questions. Because the search question is often based on operations on the status, bit operations are often particularly effective, and the effect after optimization can be obvious to all.

Example 1: poj 1324
Based on the question, determine the representation of the State (record the current state of the Snake head X, Y value and the remaining part of the motion state ), generally, it is easy to use an array (for example, X [n-1], n is the number of snake nodes, and N [0] is the movement trend of the second node) to represent the remaining part of the motion state, and the value of an array element is 0, 1, 2, 3, that is, four directions. Each time a snake moves, the array needs to be updated. The update is very simple, except for the update of N [0, the remaining N [I] is equal to the N [I-1] (I> 1) of the previous round; if an array is used, it must be updated with a loop, this will lead to unsatisfactory program speed, so we can think of using bitwise operations to simulate it. In short, it is to store a variable compressed from the original array, the original value range of any array element is 0 ~ 3. In binary format, 00 ~ 11. It takes up to 2 bits. In this way, we can perform this operation through shift operations and or operations.

TIPS: If you have a direction sequence A0, A1, A2, A3 ,.... A (n-1) is placed in variable B and expressed as an in the nth bit. You can use the following loop:
B = 0;
For (I = 0; I <n; I ++)
B = (B <2) | A [I];
That is to say, each time you move the processed bit segment to two places, in this way, two zeros will be automatically filled at the low level, and one | operation will be used, and a new value will be put into the variable.

If you want to restore data from B, you can use the> method.

For (I = 0; I <n; I ++)
A [n-1-i] = (B> (I * 2) & 3;
Shift removes the low-level elements, while & 3 removes the elements that move to the low-level elements.

The more efficient method is (the premise of the two methods is not to change the value of B)

T = B;
For (I = 0; I <n; I ++ ){
A [n-1-i] = T & 3;
T> = 2;
}
The reason for the efficiency is described at the beginning of the post.

In the bit segment operation that indicates the status, it is best to set the variable to the unsigned int (short) type, because the signed type (the highest bit of a negative number (symbol bit) is 1)> when an operation is added to a negative number, 1 rather than 0 is introduced to the right. This is basically not the operation you want.

Example 2: poj 3460 booksort
This question can be applied when the book is exchanged. Maybe you think it is more intuitive to use Arrays for simulation, but you may not think so if you look at the implementation below.
The maximum number of books is 15,
In this way, a 64-bit integer is created. Each 4-bit integer represents a book.
First, pre-process and calculate two tables.
Extract [I] [J] and clear [I] [J] respectively indicate to take out or clear the I to J book on the bookshelf. Obviously, in the I to J section, all spaces are 1, the other part is 0, while clear [I] [J] is the inverse of extract [I] [J ].

The calculation method is as follows:

Typedef unsigned long longint;
Const longint base = 15; // This is important. The normal constant 15 is an integer and will cross the border in the following operations

For (I = 0; I <15; I ++ ){
Extract [I] [I] = base <(I * 4 );
Clear [I] [I] = ~ Extract [I] [I];
For (j = I + 1; j <15; J ++ ){
Extract [I] [J] = extract [I] [J-1] | (base <(J * 4 ));
Clear [I] [J] = ~ Extract [I] [J];
}
}
After calculation, the exchange of books becomes very simple.

Inline void transposition (longint & cur, longint & next, Int & I, Int & K, Int & J) {// I, replacement of K and k + 1, C segments
Next = cur & clear [I] [J];
Next | = (cur & Extract [I] [k]) <(J-k) <2 );
Next | = (cur & Extract [k + 1] [J])> (k-I + 1) <2 );
}

First, assign the values after I to J are all cleared to next, and take out the books of I and K segments and move them to a high position (the difference value is (J-k) * 4). Likewise, then the K + I to J segment value is removed to the low position.
This is clear and clear, and if an array is used, 10 + rows of statements are indispensable and easy to make mistakes.

Example 3: hoj Eight Digital Problems
Http://acm.hnu.cn: 8080/online /? Action = problem & type = show & id = 10466.
I did not use bitwise operations to solve this problem faster, saving a little space.
In addition, the test data for this question is very strong.

A 64-bit integer is used to represent the entire State. Each 4-bit represents a digital (0 ~ 8). If the char array is used, 9 characters are used and 72 characters are used.
Calculate the mask used to retrieve and clear a certain bit.
This method is more advantageous than using an integer such as 123480567, because it is obvious that the retrieval of a certain digit is very fast and does not require time-consuming operations such as % 10 and/10, if this is done, do not use STL map. I tried it once, rather slowly. It's better to honestly expand it. However, it is similar to the speed of opening a char array (although the Assignment time is too large, but after all others are arrays, haha, if every 4 bits are used as an array of units, it would be nice-don't tell me the bit segments defined in struct, that's quite slow ).

Recently, a poj 2286 operation can be used for bitwise operations, but it seems a little troublesome and useless. The result is replaced by a Pascal sub-Super, when the status is good, you need to change this question to a bitwise operation, so you do not believe that the problem is less than 0 ms.

Updating...

Category 2: String hash and search

We all know about the Rabin-Karp Algorithm. In fact, one of the reasons for the slow implementation of Rabin-Karp is that there are too many modulo operations. In fact, we can use bitwise operations to implicitly modulo

The original link is as follows: http://www-igm.univ-mlv.fr /~ Lecroq/string/node5.html # section0050

It has an int type, and each time it replaces multiplication with shift, and because the integer has a range, but the shift exceeds the range, the effect is equivalent to a mod int_max operation. In this way, the speed is doubled.

Poj 2513 colored sticks can be used to consider the hash of this method, and its conflicts are also very small. Of course, there is a more efficient hash algorithm for string bit operations. For some reason, I will not talk about it here.

// To be continued

Category 3:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.