您的位置:首页 > 产品设计 > UI/UE

UESTC 491 Tricks in Bits (暴力回溯 + 剪枝)

2016-06-03 21:32 519 查看

Tricks in Bits

Time Limit: 3000/1000MS (Java/Others)     Memory Limit: 65535/65535KB (Java/Others)

Given N

unsigned 64

-bit integers, you can
bitwise NOT
each or not. Then you need to add operations selected from
bitwise 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

(no more than 1000
), 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 n

integers follow in the next line.

Output

For every test case, you should output
Case #k:
first, where
k

indicates the case number and counts from
1

. Then output the answer.

Sample input and output

Sample InputSample 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
bitwise NOT
, is a unary operation that performs logical negation on each bit, forming the ones' complement of the given binary value. Digits which were0

become 1
, and vice versa.

The
bitwise 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

if the first bit is 1
or the second bit is 1
or both bits are 1;
otherwise, the result is 0
.

The
bitwise XOR
takes two bit patterns of equal length and performs the
logical XOR
operation on each pair of corresponding bits. The result in each position is1

if the two bits are different, and
0

if 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: