Codeforces Round #827 (Div. 4) G. Orray 解题报告

原题链接:

Problem - G - Codeforces

题目描述:

You are given an array aa consisting of nn nonnegative integers.

Let's define the prefix OR array bb as the array bi=a1 OR a2 OR … OR aibi=a1 OR a2 OR … OR ai, where OROR represents the bitwise OR operation. In other words, the array bb is formed by computing the OROR of every prefix of aa.

You are asked to rearrange the elements of the array aa in such a way that its prefix OR array is lexicographically maximum.

An array xx is lexicographically greater than an array yy if in the first position where xx and yy differ, xi>yixi>yi.

Input

The first line of the input contains a single integer tt (1≤t≤1001≤t≤100) — the number of test cases. The description of test cases follows.

The first line of each test case contains a single integer nn (1≤n≤2⋅1051≤n≤2⋅105) — the length of the array aa.

The second line of each test case contains nn nonnegative integers a1,…,ana1,…,an (0≤ai≤1090≤ai≤109).

It is guaranteed that the sum of nn over all test cases does not exceed 2⋅1052⋅105.

Output

For each test case print nn integers — any rearrangement of the array aa that obtains the lexicographically maximum prefix OR array.

题目大意:

给你一个长度为n的数组,问如何重新排列,保证其或的前缀数组尽量大,也就是前缀或的字典序尽量大。

解题思路:

如果当前前缀或为ans,那么我们肯定是想从剩下的元素里边挑一个或运算之后结果更大的。因为题目给的ai最大为1e9,最多只有30个二进制位,所以最多只需要考虑排好前30个,后边的无所谓(因为过程中肯定是会让ans越来越大的,最大也就是让30位全部变为1,如果30次还没有变成全1,那再往后也没有可能继续增加)。最极端的情况下1e5个数,进行30次sort是完全可以承受的。

代码(CPP):

#include <bits/stdc++.h>
using namespace std;
#define endl '\n'
#define int long long
typedef unsigned long long ull;
const int maxn = 2e5 + 10;
const int INF = 0x3fffffff;
int ans = 0, n, a[maxn];

bool cmp(int a, int b)
{
    return (ans | a) > (ans | b);
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cout << fixed;
    cout.precision(18);

    int t;
    cin >> t;
    while (t--)
    {
        ans = 0LL;
        cin >> n;
        for (int i = 1; i <= n; i++)
            cin >> a[i];

        int cnt = min(30LL, n);
        for (int i = 1; i <= cnt; i++)
        {
            sort(a + i, a + 1 + n, cmp);
            ans |= a[i];
        }
        for (int i = 1; i <= n; i++)
        {
            if(i != 1)
                cout << " ";
            cout << a[i];
        }
        cout << endl;
    }
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值