P17079 Lab 题解

· · 题解

题解

吐槽:#define unsigned long long。

题目大意

给定一个长度为 n 的非负整数序列 A。

进行任意次以下操作:选择一个下标 i 和一个整数 x 令

A_i \gets A_i - x, A_{i+1} \gets A_{i+1} \oplus x

使得 A_1 = A_2 = \cdots = A_{n-1} = 0,并且最大化 A_n 的值。

思路

首先,我们知道,异或两次等于没异或。

肯定最后每个数都要异或在一起,但是不能把每一位都异或,只需要把当前不是 1 的变成 1 即可,但是这样有时候会多出几位 1,我们可以把这几位 1 补充给比它更低的 0 位上,最后余下的数就不停反复进行 x=1 的操作。

复杂度 \mathcal{O}(n \log m),其中 m = \max_{i=1}^n A_i。

代码

#include<bits/stdc++.h>
using namespace std;
//#define int unsigned long long
struct RandomNumberGenerator {
    private:
        unsigned long long state;
        static constexpr unsigned long long a = 6364136223846793005ULL;
        static constexpr unsigned long long c = 1442695040888963407ULL;
        unsigned long long k;
        vector<unsigned long long> p;
    public:
        explicit RandomNumberGenerator(unsigned long long seed, int k_, const vector<unsigned long long>& p_)
            : state(seed), k(k_), p(p_) {
            if (k > 32) k = 32;
            if (p.size() < static_cast<size_t>(k)) {
                p.resize(k, 0);
            }
        }
        unsigned long long next() {
            state = state * a + c;
            return state;
        }
        unsigned long long operator()() {
            unsigned long long result = 0;
            for (int i = 0; i < k; i++) {
                unsigned long long rand_val = next();
                if (rand_val < p[i]) {
                    result |= (1ULL << i);
                }
            }
            return result;
        }
};
int A[1000006];
signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0),cout.tie(0);
    int n,k,seed;
#ifdef ONLINE_JUDGE
    cin>>n>>k>>seed;
    vector<unsigned long long>p(k);
    for(int i=0; i<k; i++)cin>>p[i];
    RandomNumberGenerator rnd(seed,k,p);
    for(int i=1; i<=n; i++)A[i]=rnd();
#else
    cin>>n;
    for(int i=1; i<=n; i++) {
        cin>>A[i];
    }
#endif
    int s=0,sss=0;
    for(int i=1; i<=n; i++) {
        int tmp=s&A[i];
        s|=A[i];
        int len=log2(max(s,tmp));
        for(int j=len;j>=1;j--){
            if((s&(1<<j))==0){
                if(tmp>=(1<<j)){
                    tmp-=i<<j;
                    s|=(1<<j);
                }
            }
        }
        if(tmp&1)s^=1;
    }
    cout<<s;
}