A. Anu Has a Function
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
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.
题目大意:给你n个数字,使得 (f(…f(f(a1,a2),a3),…an−1),an) 的值最大 f(x, y) = x|y - y
题解:当x的某一位只出现一次1,结果才是1,比如 10|7 - 7 = 8
1010|0111 = 1111 - 0111 = 1000
所以:我们只需找到存储中最大的位上是1的元素即可(由二进制的性质所有后面的位数相加的值不可能比前面的大)
AC代码:
#include<bits/stdc++.h>
#define rep(i, aa, bb) for(int i = aa; i <= bb; i ++)
#define per(i, aaa, bbb) for(int i = aaa; i >= bbb; i --)
#define int long long
const int maxn = 1e5 + 10;
using namespace std;
typedef long long ll;
int a[maxn];
signed main()
{
int T = 1;
// cin >> T;
while(T --){
int n,k = 1;
cin >> n;
rep(i, 1, n){
cin >> a[i];
}
per(j, 32, 0){
int cnt = 0;
rep(i, 1, n){
if((a[i] >> j)&1){ //从最高位向最低位遍历,如果只出现,一次1,那就是这位
cnt++;
k=i;
if(cnt>1)
break;
}
}
if(cnt == 1)break;
}
cout << a[k];
rep(i, 1, k - 1){
cout << " " << a[i];
}
rep(i, k + 1, n){
cout << " " << a[i];
}
printf("\n");
}
return 0;
}