Codeforces Round #618 (Div. 1) A. Anu Has a Function
Anu has created her own function 𝑓: 𝑓(𝑥,𝑦)=(𝑥|𝑦)−𝑦 where | denotes the bitwise OR operation. For example, 𝑓(11,6)=(11|6)−6=15−6=9. It can be proved that for any nonnegative numbers 𝑥 and 𝑦 value of 𝑓(𝑥,𝑦) 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 [𝑎1,𝑎2,…,𝑎𝑛] is defined as 𝑓(𝑓(…𝑓(𝑓(𝑎1,𝑎2),𝑎3),…𝑎𝑛−1),𝑎𝑛) (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 𝑛 (1≤𝑛≤105).
The second line contains 𝑛 integers 𝑎1,𝑎2,…,𝑎𝑛 (0≤𝑎𝑖≤109). Elements of the array are not guaranteed to be different.
Output
Output 𝑛 integers, the reordering of the array with maximum value. If there are multiple answers, print any.
Examples
input
4
4 0 11 6
output
11 6 4 0
input
1
13
output
13
Note
In the first testcase, value of the array [11,6,4,0] is 𝑓(𝑓(𝑓(11,6),4),0)=𝑓(𝑓(9,4),0)=𝑓(9,0)=9.
[11,4,0,6] is also a valid answer.
解题思路
𝑓(𝑥,𝑦)=(𝑥|𝑦)−𝑦
以二进制看,结果就是x的某位上有的而y没有的结果
举个例子:
x = 01011
y = 01100
x|y = 01111
x|y-y = 00011
所以𝑓(𝑓(…𝑓(𝑓(𝑎1,𝑎2),𝑎3),…𝑎𝑛−1),𝑎𝑛)就是只在a1的二进制位有的而a2,a3,…,an-1,an在那个二进制位没有。
/// @author zhaolu
#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include <set>
#include <map>
#include <list>
#include <stack>
#include <queue>
#include <vector>
#include <sstream>
#include <algorithm>
#define rep(i,a,b) for(int i=a;i<b;++i)
#define repe(i,a,b) for(int i=a;i<=b;++i)
#define per(i,a,b) for(int i=a;i>=b;--i)
#define clc(a,b) memset(a,b,sizeof(a))
#define INF (0x3f3f3f3f)
#define MOD (1000000007)
#define MAX (100000)
#define LEN (MAX+10)
typedef long long ll;
using namespace std;
int n,ans;
int a[LEN];
int b[LEN];
int cnt[40];
void fun(int x)
{
int idx=0;
while(x)
{
if(x&1) ++cnt[idx];
x>>=1;
++idx;
}
}
int main()
{
scanf("%d",&n);
rep(i,0,n)
{
scanf("%d",&a[i]);
fun(a[i]);
}
ans=0;
rep(i,0,n)
{
int x=a[i];
for(int idx=0,v=1;x;x>>=1,v<<=1,++idx)
{
if((x&1)&&cnt[idx]==1)
b[i]+=v;
}
if(b[i]>=b[ans]) ans=i;
}
printf("%d",a[ans]);
rep(i,0,n) if(ans!=i) printf(" %d",a[i]);
printf("\n");
return 0;
}