Codeforces——C. Anu Has a Function

折月煮酒 提交于 2020-02-12 02:18:23

Codeforces——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.

Examples

input

4
4 0 11 6

output

11 6 4 0

input

1
13

output

1
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(f(…f(f(a1,a2),a3),…an−1),an)的值最大。

分析

把每个数转化成二进制来看,我们也不用特意去计算每个数有几位,可以从第30位(从左往右)开始,当遇到第一个在这一位上只有一个数是1的数时,即可退出,因为如果这一位上有多个数是1的话,到最后都会被消掉。

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
int a[100010];
int main()
{
	int n,cnt,k,t;
	cin>>n;
	for(int i=1;i<=n;i++){
		scanf("%d",&a[i]);
	}
	for(int j=30;j>=0;j--){
		cnt=0;
		for(int i=1;i<=n;i++){
			if((a[i]>>j)&1){
				cnt++;
				k=i;
			}
		}
		if(cnt==1){
			break;
		}
	}
	if(cnt==1){
		t=a[1];
		a[1]=a[k];
		a[k]=t;
	}
	for(int i=1;i<=n;i++){
		if(i!=n){
			printf("%d ",a[i]);
		}
		else{
			printf("%d\n",a[i]);
		}
	}
	return 0;
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!