CF 280B -——Maximum Xor Secondary(單調棧)
Bike loves looking for the second maximum element in the sequence. The second maximum element in the sequence of distinct numbers x1, x2, ..., xk (k > 1) is such maximum element xj, that the following inequality holds: .
The lucky number of the sequence of distinct positive integers x
You've got a sequence of distinct positive integers s1, s2, ..., sn (n > 1). Let's denote sequence sl, sl + 1, ..., s
Note that as all numbers in sequence s are distinct, all the given definitions make sence.
Input
The first line contains integer n (1 < n
Output
Print a single integer — the maximum lucky number among all lucky numbers of sequences s[l..r].
Examples
Input
5
5 2 1 4 3
Output
7
Input
5
9 8 3 5 7
Output
15
Note
For the first sample you can choose s[4..5] = {4, 3} and its lucky number is (4 xor 3) = 7. You can also choose s[1..2].
For the second sample you must choose s[2..5] = {8, 3, 5, 7}.
題意:給一個長度為 n 的序列,元素不重複,求任意區間中的最大元素與次大元素的異或值,然後再取這些值的最大值,注意區間長度任意。
題解:如果暴力的話是 O(n ^ 2) 的複雜度,顯然不行,所以就需要用單調棧維護一下,O(n)解決,找到第一個比它大的數,看程式碼吧!!
#include <iostream>
#include <cstdio>
#include <stack>
using namespace std;
const int MAX = 1e5+100;
typedef long long ll;
ll a[MAX];
stack<ll> s;
int main(){
int n;
scanf("%d",&n);
for (int i = 0; i < n;i++){
scanf("%lld",&a[i]);
}
ll ans=0;
for (ll i = n-1; i >= 0;i--){
while(!s.empty()&&a[s.top()]<a[i]) s.pop();//單調棧找到第一個比它大的數 反向跑
if(!s.empty()) ans=max(ans,a[s.top()]^a[i]);
s.push(i);
}
for (ll i = 0; i < n;i++){
while(!s.empty()&&a[s.top()]<a[i]) s.pop();//單調棧找到第一個比它大的數 正向跑
if(!s.empty()) ans=max(ans,a[s.top()]^a[i]);
s.push(i);
}
// 必須兩個方向跑,要不然會有遺漏
printf("%lld\n",ans);
return 0;
}