题意:
1423 最大二“货”
1.0 秒 131,072.0 KB 80 分 5级题
注意,序列s中的所有数字都是不同的。
输入
单组测试数据。
第一行有一个整数n (1 < n ≤ 10^5)。
第二行包含n个不同的整数 s1, s2, …, sn (1 ≤ si ≤ 10^9)。
输出
输出所有子段的最大幸运值。
输入样例
5
5 2 1 4 3
5
9 8 3 5 7
输出样例
7
15
思路:
我的想法:
看到这道题,求所有子段的最大值和次大值的异或值。。
最大值有很多种方法可以进行求解,线段树和单调栈等。。。
次大值目前还没有求解的办法555
还有一个问题是题目要求所有子段555
正解:
单调递减栈求最大值和次大值。。
单调栈性质:每次push进去一个数,就可以得到一段区间的最大值和次大值
但是我们要正反两次求单调递减栈,因为最大值可能在次大值的左边,也可能在右边
代码实现:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<stack>
using namespace std;
typedef long long ll;
typedef pair<int,int> pii;
const int maxn = 2e5 + 5;
int n;
ll s[maxn];
stack<ll> st;
int main(){
scanf("%d",&n);
for(int i = 1;i <= n;i++){
scanf("%lld",&s[i]);
}
ll ans = 0;
while(!st.empty()) st.pop();
for(int i = 1;i <= n;i++){
while(!st.empty()&&s[i] > s[st.top()]) st.pop();
if(!st.empty()){
ans = max(ans,s[i]^s[st.top()]);
}
st.push(i);
}
while(!st.empty()) st.pop();
for(int i = n;i >= 1;i--){
while(!st.empty()&&s[i] > s[st.top()]) st.pop();
if(!st.empty()){
ans = max(ans,s[i]^s[st.top()]);
}
st.push(i);
}
printf("%lld\n",ans);
return 0;
}