解題報告 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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章