跳到正文

题解

P17079 Lab 题解

yzyUUU约 4 分钟
原文
文章信息与版本

文章信息

收录
2026年7月10日
更新
2026年7月17日
篇幅
约 4 分钟
题目
P17079

版本

  1. v3当前
  2. v2
  3. v1

题解

吐槽:#define unsigned long long。

题目大意

给定一个长度为 nn 的非负整数序列 AA。

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

Ai←Ai−x,Ai+1←Ai+1⊕xA_i \gets A_i - x, A_{i+1} \gets A_{i+1} \oplus x

使得 A1=A2=⋯=An−1=0A_1 = A_2 = \cdots = A_{n-1} = 0,并且最大化 AnA_n 的值。

思路

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

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

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

代码

C++
#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;
}
原文