2021 - 09 - 02 Anu Has a Function

6 篇文章 0 订阅
1 篇文章 0 订阅

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值