解题报告 CodeForces - 1300C Anu Has a Function

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 xx and yy 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 [a_{1},a_{2},...,a_{n}] is defined asf(f(...f(f(a_{1},a_{2}),a_{3}),...a_{n-1}),a_{n}) )(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\leq n\leq10 ^{5}).

The second line contains nn integers a_{1},a_{2},a_{3},...a_{n} (1\leq a[i]\leq10 ^{9}). 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

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] 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:f(x,y)=x|y-y,以及该函数对数组的计算方式f(f(...f(f(a_{1},a_{2}),a_{3}),...a_{n-1}),a_{n}),输入一个数组,重新排列该数组使得该数组在函数作用下的值最大,输出重新排列后的数组。

思考过程:

1.该题目中的重点是这个函数,所以我们要先思考这个函数的本质是什么。显而易见,将给定的x,y用二进制表示,所得结果的二进制表示的每一位:当且仅当x在该位上为1且y在该位上为0时结果的该位上才为1(函数的作用是用y的1消去x的1)不显而易见的话写一写就显而易见了

2.那么和计算顺序有什么关系呢?如果x在第k位上为1,y在第k位上为0,则f(x,y)在第k位上为1,f(y,x)在第k位上为0

3.所以我们应该尽量保证可以为1的位上为1

4.什么是可以为1的位呢?如果在所有的数中有超过1个数(>=2)第k位上是1,那么不管如何排列,第k位上的1肯定会被消去(毕竟,必有一前一后),所以可以为1的位就是所有的数的二进制表示在该位上只出现了1次1

5.如何保证结果最大呢?由于并非所有满足条件的位置都可以取到1(例如:2,8,9),所以优先保证高位上的1可以取到。于是就有了如下思路。

思路:

用数组b来保存在所有数的二进制表示下的每个位置上共出现了多少次 1,在从高位向低位遍历,如果该位可以为1就从数组中找出vis没被标记过且使该位取到1的数,如过找到了就将该数的vis标记并将该数加入ans数组。遍历完成后输出ans数组,但是往往ans中元素的个数小于n,所以还需遍历原数组a,将其中没有加入到ans数组中的数输出(这些数的vis没被标记)

代码:

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
#define maxn 100005
#define mod 998244353
#define getbit(x,y)((x)>>(y)&1)
int n,a[maxn],b[35],ans[maxn],vis[maxn];

int main()
{
    memset(vis,0,sizeof vis);
    cin>>n;
    for(int i=0;i<n;i++)
    {
        cin>>a[i];
        int tmp;
        for(int j=31;j>=0;j--)
        {
            tmp=getbit(a[i],j);
            b[j]+=tmp;
        }
    }
    int l=0;
    for(int i=31;i>=0;i--)
    {
        if(b[i]!=1)continue;
        for(int j=0;j<n;j++)
        {
            if(vis[j])continue;
            int tmp=getbit(a[j],i);
            if(tmp==1)
            {
                vis[j]=1;
                ans[l++]=a[j];
            }
        }
    }
    for(int i=0;i<l;i++)
        cout<<ans[i]<<" ";
    for(int i=0;i<n;i++)
        if(!vis[i])cout<<a[i]<<" ";
    return 0;
}

 

发布了10 篇原创文章 · 获赞 1 · 访问量 1217
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章