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