位运算-状压DP 常用技巧
@
就想取个标题
这些操作在状压DP中都很常用,灵活应用可以很好地降低码量,降低常数。
取出x的第i位:
\(y\)= (\(x\)>>(\(i\)-\(1\)))&\(1\);
将x第i位取反
\(x\) ^= \(1\)<<(\(i\)-\(1\));
将x第i位变为1
\(x\) |= \(1\)<<(\(i\)-\(1\));
将x第i位变为0
\(x\) &= ~(\(1\)<<(\(i\)-\(1\)));
将x最靠右的1变成0
\(x\) = \(x\)&(\(x\)-1);
取出x最靠右的1
\(y\) = \(x\)&(-\(x\));
这也是树状数组中我们熟知的\(lowbit\)
把最靠右的0变成1
\(x\)|=\(x\)+\(1\)
判断是否有两个连续的1
\(if\)(\(x\)&(\(x\)<<\(1\))) \(cout\)<<"\(YES\)";
判断是否有\(n\)个连续的\(1\)
\(if\)(\(x\)&(\(x\)<<\(1\))&&\(x\)&(\(x\)<<\(2\))...&&\(x\)&(\(x\)<<\(n\)-\(1\)))
枚举子集
定义\(sta\)为初始状态
\(for\)( \(int\) \(x\) = \(sta\) ; \(x\) ; \(x\) = ( ( \(x\) - \(1\) )&\(sta\)) )
\(cout\)<<\(x\);