Tricks in Bits
Time Limit: 3000/1000MS (Java/Others) Memory Limit: 65535/65535KB (Java/Others)
Given N
-bit integers, you can bitwise NOT
each or not. Then you need to add operations selected frombitwise XOR
, bitwise OR
and bitwise AND
, between any two successive integers and calculate the result. Your job is to make the result as small as possible.
Input
The first line of the input is T
), which stands for the number of test cases you need to solve.
Then T
blocks follow. The first line of each block contains a single number N ( 1≤N≤100 ) indicating the number of unsigned 64 -bit integers. Then nintegers follow in the next line.
Output
For every test case, you should output Case #k:
first, where
k
. Then output the answer.
Sample input and output
Sample Input | Sample Output |
---|---|
2 3 1 2 3 2 3 6 | Case #1: 0 Case #2: 1 |
Hint
- Case # 1
- :
1|2^3 = 0
- Case #
2
- :
3&(~6) = 1
The
become 1bitwise NOT
, is a unary operation that performs logical negation on each bit, forming the ones' complement of the given binary value. Digits which were 0, and vice versa.
The
if the first bit is 1 or the second bit is 1 or both bits are 1 ; otherwise, the result is 0bitwise OR
takes two bit patterns of equal length, and produces another one of the same length by matching up corresponding bits (the first of each; the second of each; and so on) and performing the logical inclusive or operation on each pair of corresponding bits. In each pair, the result is 1.
The
if the two bits are different, and 0bitwise XOR
takes two bit patterns of equal length and performs thelogical XOR
operation on each pair of corresponding bits. The result in each position is 1if they are the same.
Source
Sichuan State Programming Contest 2011
大体题意:
给你n 个数,可以任意加 & | ^ ~ 等位运算,使得最后的结果尽可能小,求出最后的结果!
思路:
除了~是对自身的用的意外,其余三个都是两个数之间进行运算。
那么直接暴力三个运算符 加上自身一个取反,总共有6个dfs。但是这样做会超时,需要加一个剪枝, 那么就是当答案或当前的暴力的值已经到0了 那么就没必要在回溯了。直接return 了就。
有坑的话,就是注意运算符的优先级吧~~~~~~~~~= =!!
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; typedef unsigned long long llu; const int maxn = 100 + 5; const llu INF = (1 << 63) - 1; int n,cnt; llu a[maxn],ans; void dfs(llu num,int cur){ if (!ans || !num){ ans = 0; return; } if (cur == n){ ans = min(ans,num); return; } dfs(num | a[cur],cur+1); dfs(num & a[cur],cur+1); dfs(num ^ a[cur],cur+1); dfs(num | (~a[cur]),cur+1); dfs(num & (~a[cur]),cur+1); dfs(num ^ (~a[cur]),cur+1); } int main(){ int T; scanf("%d",&T); while(T--){ scanf("%d",&n); for (int i = 0; i < n; ++i)scanf("%llu",&a[i]); ans = INF; dfs(~a[0],1); dfs(a[0],1); printf("Case #%d: %llu\n",++cnt,ans); } return 0; }
- :