Codeforces Round #618 (Div. 2) C题

Anu Has a Function

Anu has created her own function f: f(x,y)=(x|y)−y where | denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers x and y value of f(x,y) is also nonnegative.

She would like to research more about this function and has created multiple problems for herself. But she isn’t able to solve all of them and needs your help. Here is one of these problems.

A value of an array [a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an) (see notes). You are given an array with not necessarily distinct elements. How should you reorder its elements so that the value of the array is maximal possible?

Input
The first line contains a single integer n (1≤n≤105).

The second line contains n integers a1,a2,…,an (0≤ai≤109). Elements of the array are not guaranteed to be different.

Output
Output n integers, the reordering of the array with maximum value. If there are multiple answers, print any.


可以说是一道贪心题, (x|y)-y 可以发现这样得到的值最大为x,最小为x-y;

最大的情况下,说明x和y的二进制位1的位置都不相同;

最小的情况下,说明x和y的二进制位1的位置都相同;

所以要保证的是尽量找到一个大的数,这个数存在二进制位1的位置与其他所有数1的位置都不相同,这个数放在开头,保证了之后所有的数跟它 或 运算都增大;

代码:

#include<bits/stdc++.h>
#define ll long long
#define pa pair<int,int>
#define lson k<<1
#define rson k<<1|1
//ios::sync_with_stdio(false);
using namespace std;
const int N=100100;
const int M=200100;
const ll mod=1e9+7;
int a[N];
int main(){
    ios::sync_with_stdio(false);
    int n;
    cin>>n;
    for(int i=1;i<=n;i++) cin>>a[i];
    int ans=0;
    for(int i=30;i>=0;i--){
    	int sum=0;
    	for(int j=1;j<=n;j++){
    		if((a[j]>>i)&1) sum++,ans=j;
		}
		if(sum==1) break;
	}
	if(ans){
		int t;
		t=a[1];
		a[1]=a[ans];
		a[ans]=t;
	}
	for(int i=1;i<=n;i++) cout<<a[i]<<" ";
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值