状态压缩DP常遇到的位运算
位操作一共有6种形式:<<,>>,&,|,^,~;
1.左移操作符<<:左移操作符将整数的二进制向左移若干位,将最高若干位挤掉,并在低位补0
如:
int a=3; //a=000000000000000000000000000000011=3 int b=a<<1; //b=000000000000000000000000000000110=6 int c=a<<3; //c=000000000000000000000000000001100=12
实际上:a<<1,a右移1位表示a*2,a<<m表示a*2^m
2.右移操作符>>:右移操作符将整数的二进制向右移若干位,将最低若干位挤掉,并在高位补0或者1
int a =10; //a=000000000000000000000000000001010=10
int b = a>>1; //b=000000000000000000000000000000101=5 int c = a >> 2; //c=000000000000000000000000000000010=2
右移操作符就是不断的做除2^m的运算。
3.位与操作&:位与操作是将两个数的二进制的每一位左与操作:例如:
int a = 6, b = 10;
int c = a&b; //则 c = 2;
//(000000000000000000000000000000110)&(000000000000000000000000000001010) //=000000000000000000000000000000010
4.位或操作符|:将两个整数二进制的每一位做或操作运算。
int a = 6, b = 10; int c = a|b; //则 c=14; //(000000000000000000000000000000110)1(000000000000000000000000000001010) //=000000000000000000000000000001110
5.位异或操作符^:将两个操作数每一位做异或操作(相同为0,不同为1)
int a = 6, b = 10; int c = a^b; //则 =12; //(000000000000000000000000000000110)^(000000000000000000000000000001010) //=000000000000000000000000000001100
6位反操作~:将操作数的二进制每一位按位取反,0变为1,1变为0.
int a = 6; int b = ~a; //b=-7 //b=~(000000000000000000000000000000110)=11111111111111111111111111111001
位操作相对乘法快很多,将所有对2的乘法运算转换为位移运算,可提高程序的运行效率。在C/C++中还有一类复合的位运算符:&=、!=、>>=、<<=和^=
其实a&=b;等价于a=a&b;依次类推。