Codeforces Round #772 (Div. 2) A. Min Or Sum

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]:

  1. 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].

  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;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值