C. Anu Has a Function
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
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.
Examples
inputCopy
4
4 0 11 6
outputCopy
11 6 4 0
inputCopy
1
13
outputCopy
13
Note
In the first testcase, value of the array [11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.
[11,4,0,6] is also a valid answer.
思路:f(x,y)=(x|y)-y=x&(~y),所以题目中 f(f(…f(f(a1,a2),a3),…an−1),an)即a1& (~a2)&( ~ a3)…&(~ an),,因为位运算是按位运算的,所以要使这个式子的值最大,就要尽可能让高位的尽量为1,而不是0,如何尽可能让高位的比特为1呢?我们可以从高位向低位遍历,假设我们现在遍历到了第i位,这个时候我们发现这个数组中只有一个元素(假设为a1)第i位为1,而其他元素的第i位为0,这时按位与的结果才可能使第i位为1,其他情况都不可能。所以我们要找出这个所谓的a1,把它排在第一位,其他元素的顺序都无所谓了。怎么找这个a1,从高位向低位依次遍历找出这个a1就行了。不说多了,上代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <ctype.h>
#include <cstdlib>
#define ll long long int
using namespace std;
int main()
{
int n,k;scanf("%d",&n);
ll a[100008];
for(int i=1;i<=n;i++)scanf("%lld",&a[i]);
for(int j=32;j>=0;j--){
int cnt=0;
for(int i=1;i<=n;i++)
{
if((a[i]>>j)&1){cnt++;k=i;if(cnt>1)break;}
}
if(cnt==1)break;
}
printf("%lld",a[k]);
for(int i=1;i<k;i++){printf(" ");printf("%lld",a[i]);}
for(int i=k+1;i<=n;i++){printf(" ");printf("%lld",a[i]);}
printf("\n");
return 0;
}