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 
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;
}

你可能感兴趣的:(#,Codeforces,算法,c++,开发语言)