Codeforces Round #618

C. 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.

Examples
inputCopy
4
4 0 11 6
outputCopy
11 6 4 0
inputCopy
1
13
outputCopy
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(a,b)这个操作的本质就是,对于b中为1的位数,将其在a中对应的位数变为0。用式子表达即:f(a,b)=a&(~b)。容易观察到,关键点是在第一个数,后面n-1个数的排序都是不影响结果的。用cnt数组来保存这n个数中第i位为1的数量。从最高位开始找,找到第一个cnt为1的位数,把那个数提前,其他随意输出,若没有找到,就代表,每个元素都是0,随意输出即可。

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int maxn=1e5+10;
ll a[maxn],cnt[50];//cnt存第i位是1的数的个数
void solve()
{
	int n;
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
		scanf("%lld",&a[i]);
		for(int j=0;j<=31;j++)
			if((a[i]>>j)&1)//看这个数第31-j位是不是1!!!!!
				cnt[j]++;
	}
	for (ll i = 31; i>=0; i--)
    {//从最高位开始找,如果这个位数的个数大于1或为0,那么早晚变为0,
        if (cnt[i] == 1)//如果这个位数等于1的话,一定要保下这个1,即把它放到最前面
        {
            int pos = 0;
            for (ll j = 1; j <= n; j++)
                if ((a[j] >> i) & 1)
                    pos = j;//找到这个数的编号pos
            printf("%lld ", a[pos]);
            for (int j = 1; j <pos; j++)//除掉这个数以外,任意顺序输出
                printf("%lld ", a[j]);
            for (int j = pos + 1; j <= n; j++)
                printf("%lld ", a[j]);
            return;
        }
    }
    //如果所有位都是0,那就直接输出
    for (ll i = 1; i <= n; i++)
        printf("%lld ", a[i]);
	
}
int main()
{
/*
	int t;
    scanf("%d",&t);
    while(t--)
*/
    solve();
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值