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)/~

发布了414 篇原创文章 · 获赞 23 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/starlet_kiss/article/details/104261083