A. Min Or Sum
time limit per test:1 second
memory limit per test:256 megabytes
inputstandard input
outputstandard output
题目描述
You are given an array a of size n.
You can perform the following operation on the array:
Choose two different integers i,j (1≤i<j≤n), replace ai with x and aj with y. In order not to break the array, ai|aj=x|y must be held, where | denotes the bitwise OR operation. Notice that x and y are non-negative integers.
Please output the minimum sum of the array you can get after using the operation above any number of times.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1≤t≤1000). Description of the test cases follows.
The first line of each test case contains an integer n (2≤n≤100) — the size of array a.
The second line of each test case contains n integers a1,a2,…,an (0≤ai<230).
Output
For each test case, print one number in a line — the minimum possible sum of the array.
Example
input
4
3
1 3 2
5
1 2 4 8 16
2
6 6
3
3 5 6
output
3
31
6
7
Note
In the first example, you can perform the following operations to obtain the array [1,0,2]:
-
choose i=1,j=2, change a1=1 and a2=2, it’s valid since 1|3=1|2. The array becomes [1,2,2].
-
choose i=2,j=3, change a2=0 and a3=2, it’s valid since 2|2=0|2. The array becomes [1,0,2].
We can prove that the minimum sum is 1+0+2=3
In the second example, We don’t need any operations.
可以执行的操作:选择 i,j (1≤i<j≤n),将a[i]替换成x,a[j]替换成y,且x,y要满足a[i]|a[j]=x|y。
操作可以执行任意次,要求输出数组和最小。
因为n的数据范围比较小,所以直接双for暴力。如果当前a[i]|a[j]的值比a[i]+a[j]的值小,则将0和a[i]+a[j]分别赋给a[i],a[j] (即x=0,y=a[i]+a[j])。
AC Code
#include<bits/stdc++.h>
using namespace std;
#define IOS ios::sync_with_stdio(false)
typedef long long ll;
const int N=110;
ll a[N];
int main(){
IOS;
ll t,n;
while(cin>>t){
while(t--){
cin>>n;
for(int i=0;i<n;i++){
cin>>a[i];
}
ll ans=0;
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){//i<j
ll k=a[i]|a[j];
if(k>=a[i]+a[j]){//大于就跳过
continue;
}
a[i]=0;
a[j]=k;
}
}
for(int i=0;i<n;i++){
ans+=a[i];
}
cout<<ans<<endl;
}
}
return 0;
}