Codeforces Round #618 (Div. 2):C. Anu Has a Function

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

The meaning of problems
Given a formula: f (x, y) = (x | y) -y
given number n, the number n requires these arbitrary order, so that the result satisfies the equation of the maximum (the result of the first two do the first term) according to
the output of any of a maximum term results.

Ideas
for solving in a binary state in all of the numbers, there was once only a bit 1, and is the largest one, in the first place, the rest of the output in any order.
eg: binary state:
1,100,110,111,001,110
will be 1110 in the first place.

AC Code

#include <bits/stdc++.h>
using namespace std;
int a[100010];
int n,cnt,k,t;
int main()
{
    scanf("%d",&n);
    for(int i=1; i<=n; i++)
        scanf("%d",&a[i]);
    for(int j=30; j>=0; j--)
    {
        cnt=0;
        for(int i=1; i<=n; i++)
            if((a[i]>>j)&1)
                cnt++,k=i;
        if(cnt==1)
            break;
    }
    if(cnt==1)
        t=a[1],a[1]=a[k],a[k]=t;
    printf("%d",a[1]);
    for(int i=2; i<=n; i++)
        printf(" %d",a[i]);
    printf("\n");
}
Published 306 original articles · won praise 105 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_43460224/article/details/104302067