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

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.

题意:给了n个数让给他排序后 按照题中的公式最大

思路:很明显 当前这个数只对当前有影响,对于每个数二进制来看 都是32位,从最高位开始去看每一位中,该二进制位置位1的个数是不是只有1个 只有一个的话 ,就对答案有贡献,放到前面即可,其他的随便排序都行
举个例子 32 32 3 排序后应该是3 32 32 答案为3

#include<bits/stdc++.h>
using namespace std;
int a[100005];
int c[100005][32];
int v[100005];
int main()
{
    int n;cin>>n;
    for(int i=1;i<=n;i++){
        cin>>a[i];
        for(int j=0;j<=31;j++)
        {
            c[i][j]=(a[i]>>j)&1;
        }
    }
    int k=0;
    vector<int> q;
    for(int i=31;i>=0;i--)
    {
        int sum=0,w=0;
        for(int j=1;j<=n;j++){

            if(c[j][i]&1)
            {
                sum++;
                w=j;
            }
        }
        if(sum==1&&!v[w]) q.push_back(a[w]),v[w]=1;
    }
    for(int i=0;i<q.size();i++) cout<<q[i]<<" ";
    for(int i=1;i<=n;i++){
        if(!v[i]) cout<<a[i]<<" ";
    }

   return 0;
}

全部评论

相关推荐

醉蟀:你不干有的是人干
点赞 评论 收藏
分享
06-26 17:24
已编辑
宁波大学 Java
迷失西雅图:别给,纯kpi,别问我为什么知道
点赞 评论 收藏
分享
07-02 13:52
武汉大学 golang
骗你的不露头也秒
牛客87776816...:😃查看图片
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务