Anu Has a Function CodeForces - 1300C(二进制位运算)

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=x&(~y),可以写成这种形式。
那么我们就去求x1&(~x2)&( ~x3)&…&( ~xn)最大的最优排列顺序。
既然用到了位运算就要转化成二进制去求。观察上面那个式子可以发现,其实最后的结果仅由第一个数字决定的。如果有一位上仅有一个数字是1,而其他的数字在这一位上全都是0,那么将为1的那个数字排列在第一位,那么最后的结果这一位一定为1(剩下的数字在取反后这一位也是1)。我们位数由大到小来找这样的数字,那么只要找到一个这样的数字,将这一个数字安排在第一位,剩下的随便放就可以了。
代码如下:

#include<bits/stdc++.h>
#define ll long long
using namespace std;

const int maxx=1e5+100;
int a[maxx];
int n;

inline int fcs()
{
	for(int i=30;i>=0;i--)
	{
		int cnt=0;int pos;
		for(int j=1;j<=n;j++)
		{
			if((a[j]&(1<<i))) cnt++,pos=j;
		}
		if(cnt==1) return pos;//找到这样的一种数字
	}
	return 0;
}
int main()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++) scanf("%d",&a[i]);
	int pos=fcs();
	if(pos==0) for(int i=1;i<=n;i++) cout<<a[i]<<" ";
	else 
	{
		cout<<a[pos]<<" ";
		for(int i=1;i<=n;i++)
		{
			if(i!=pos) cout<<a[i]<<" ";
		}
	}
	cout<<endl;
	return 0;
}

努力加油a啊,(o)/~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

starlet_kiss

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值