Anu has created her own function ff : f(x,y)=(x|y)−yf(x,y)=(x|y)−y where || denotes the bitwise OR operation. For example, f(11,6)=(11|6)−6=15−6=9f(11,6)=(11|6)−6=15−6=9 . It can be proved that for any nonnegative numbers xx and yy value of f(x,y)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][a1,a2,…,an] is defined as f(f(…f(f(a1,a2),a3),…an−1),an)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 nn (1≤n≤1051≤n≤105 ).
The second line contains nn integers a1,a2,…,ana1,a2,…,an (0≤ai≤1090≤ai≤109 ). Elements of the array are not guaranteed to be different.
Output
Output nn 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][11,6,4,0] is f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9f(f(f(11,6),4),0)=f(f(9,4),0)=f(9,0)=9.
[11,4,0,6][11,4,0,6] is also a valid answer.
中文概要:
f(x,y)=(x|y)−y按二进制拆位发现对于第i位
若x、y第i位均为1,函数结果第i位为0
若x第i位为0,y第i位为1,函数结果第i位为0
若x第i位为1,y第i位为0,函数结果第i位为1
而对于f(f(…f(f(a1,a2),a3),…an−1),an)无论顺序怎么排 只要第i位为1的个数≥2 n次函数运算后结果第i位为0
计算f(11,7)
1 | 1 | 0 | 1 |
0 | 1 | 1 | 1 |
1 | 0 | 0 | 0 |
计算f(11,8)
1 | 1 | 0 | 1 |
1 | 0 | 0 | 0 |
0 | 1 | 0 | 1 |
可见,1对0为1,0对0为0,1对1为0,0对1为0;
则
1.若a1第i位为0 那么无论怎么排 n次函数运算后结果第i位为0
2.若a1第i位为1 遇到第二个第i位为1的数后 函数结果第i位为0 之后就变成了第一种情况
故最后答案只取决于第一个数,为第一个数中在n个数中只出现过一次的位
#include <iostream>
#include <cstdio>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <deque>
#include <vector>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include <stack>
#include <set>
#include<algorithm>
#include<iomanip>
#define SIS std::ios::sync_with_stdio(false)
#define ll long long
#define INF 0x3f3f3f3f
const int mod = 1e9 + 7;
const double esp = 1e-5;
const double PI = 3.14159265358979;
using namespace std;
const int N = 1e6 + 5;
/*int gcd(int a,int b)
{
return b==0?a:gcd(b,a%b);
}
ll _power(int a, int b)//快速幂
{
int ans=1, res=a;
while(b){
if(b&1) ans=ans*res%mod;
res=res*res%mod;
b>>=1;
}
return ans%mod;*/
int a[N];
int main() {
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 cnt = 0, pos = 0;
for (int j = 1; j <= n; j++)//1<<i 是将1左移i位,即第i位为1,其余位为0
if (a[j] & 1 << i) {// n& (1 << i)是将左移i位的1与n进行按位与,即为保留n的第i位,其余位置零
cnt++;
pos = j;
}
if (cnt == 1) {
ans = pos;
break;
}
}
if (ans == 0)
for (int i = 1; i <= n; i++)
cout << a[i] << " ";
else {
cout << a[ans] << " ";
for (int i = 1; i <= n; i++)
if (ans != i)
cout << a[i] << " ";
}
return 0;
}