感谢同校大佬 @Huxuanjie0517 提供的基础思路。 这是本做法的代码:
#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;
}核心思路是 ,这样可以避免朴素 做法中很多不必要的枚举。 但这个做法被 hack 了,于是我们尝试再进行优化。
注意到 hack 掉此代码数据的 类似于1 2 3 4 5...,这可以使得每一次枚举的 都小于 ,为了破坏 的这一特点,我们想到了随机化。
本题中 的顺序与答案无关,所以考虑随机重排 ,来破坏 递增的这一性质。
于是就可以 AC 了,并且跑的也不慢。
代码:
#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;
}