跳到正文

题解

题解:B3930 [GESP202312 五级] 烹饪问题

Lewis_44约 2 分钟
原文
文章信息与版本

文章信息

发布
2025年12月27日
收录
2025年12月28日
更新
2026年11月14日
篇幅
约 2 分钟
题目
B3930

版本

  1. v3当前
  2. v2
  3. v1

感谢同校大佬 @Huxuanjie0517 提供的基础思路。 这是本做法的代码:

C++
#include<bits/stdc++.h>
using namespace std;
int n,ans,a[1000010];
int main(){
    cin.tie(0)->ios::sync_with_stdio(0);
	cin >> n;
	for(int i = 1;i <= n;i++){
		cin >> a[i];
		if(a[i] <= ans)continue;
		for(int j = 1;j < i;j++){
			ans = max(ans,a[i] & a[j]);
		}
	}
	cout << ans;
	return 0;
}

核心思路是 x and y≤min⁡(x,y)x\ \text{and}\ y \le \min(x,y),这样可以避免朴素 O(n2)O(n^2) 做法中很多不必要的枚举。 但这个做法被 hack 了,于是我们尝试再进行优化。


注意到 hack 掉此代码数据的 aa 类似于1 2 3 4 5...,这可以使得每一次枚举的 ansans 都小于 aia_i,为了破坏 aa 的这一特点,我们想到了随机化。 本题中 aa 的顺序与答案无关,所以考虑随机重排 aa,来破坏 aa 递增的这一性质。 于是就可以 AC 了,并且跑的也不慢。


代码:

C++
#include<bits/stdc++.h>
using namespace std;
int a[1000010],n,ans;
mt19937 rnd(time(0));
int main(){
    cin.tie(0)->ios::sync_with_stdio(0);
	cin >> n;
	for(int i = 1;i <= n;i++){
		cin >> a[i];
	}
    shuffle(a + 1,a + n + 1,rnd);//打乱序列
    for(int i = 1;i <= n;i++){
        if(a[i] <= ans)continue;
		for(int j = 1;j < i;j++){
			ans = max(ans,a[i] & a[j]);
		}
    }
	cout << ans;
	return 0;
}
原文