题解:CF280B Maximum Xor Secondary
由于正求次大值比较困难,不如逆向思考。
由次大值来找最大值,即对于每个 ,找到一个 ,满足 并且 。
这项工作当然要交给单调栈来解决啦。
特别的,如果最大值在次大值的右边,你就会很开心的得到一个大大的 WA。
所以还需要反跑一遍。
AC code:
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e5+5;
stack<int>st,st1;//st正,st1反
int ans=-1e9;
int n,a[maxn];
int main(){
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
}
for(int i=1;i<=n;i++){
while(!st.empty()&&a[st.top()]<a[i]){
st.pop();//正常单调栈
}
if(!st.empty())ans=max(ans,a[st.top()]^a[i]);//找到最大值,更新答案
st.push(i);
}
for(int i=n;i>=1;i--){//反跑
while(!st1.empty()&&a[st1.top()]<a[i]){
st1.pop();//反着的单调栈
}
if(!st1.empty())ans=max(ans,a[st1.top()]^a[i]);//同上
st1.push(i);
}
cout<<ans;//撒花!!!
return 0;
}
本人(KK_SpongeBob)蒟蒻,写不出好文章,但转载请注明原文链接:https://www.cnblogs.com/OIer-QAQ/p/18575281

浙公网安备 33010602011771号