题目描述
牛牛得到一个长度为n的整数序列V,牛牛定义一段连续子序列的幸运值为这段子序列中最大值和次大值的异或值(次大值是严格的次大)。牛牛现在需要求出序列V的所有连续子序列中幸运值最大是多少。请你帮帮牛牛吧。
输入描述:
第一行一个整数n,即序列的长度。(2<= n <= 100000) 第二行n个数,依次表示这个序列每个数值V[i], (1 ≤ V[i] ≤ 10^8)且保证V[1]到V[n]中至少存在不同的两个值.
输出描述:
输出一个整数,即最大的幸运值
示例1
输入
复制
5 5 2 1 4 3
输出
复制
7
思路:本题主要是看最大和次大,那么如果一个序列 5 4 3 2 1,它需要求得就是 5 4 ,4 3, 3 2, 2 1.此四组
那我们使用递减序列,就可以将相对于ai的数,就可以得到第一个据他最近的比他大的数,第二个比他大的数他是无法取到的
因为这不符合最大,和次大,就好像 5 2 1 4 3 ,3可以和4算,但是3不可能存在和5算的情况,因为 4 比 3 大,
而距离它比较近而且比他小的数,我们是要计算的,因为小数也只能算离它最近的比他大的第一个数。(对于每一个数都要算它左右两边距离他最近的比他大的第一个数)
# include <iostream>
# include <algorithm>
# include <cstring>
# include <math.h>
# include <stdio.h>
# include <vector>
# include <map>
# include <stack>
using namespace std;
stack<int> sta;
vector<int> a;
int maxn = -1e9;
int get(int n){
for(int i = 0; i < n; i++){
int top;
if(sta.empty()){
sta.push(a[i]);
}
else{
while(!sta.empty() && (top = sta.top())){
int num = top ^ a[i];
if(num > maxn)
maxn = num;
if(a[i] < top){
//在这里存数无法让比栈中数字都大的值进去
break;
}
else{
sta.pop();
}
}
sta.push(a[i]);//在这里存数,可以保证每个数都进去。
}
}
return maxn;
}
int main(){
int n;
cin >> n;
for(int i = 0; i < n; i++){
int num;
cin >> num;
a.push_back(num);
}
cout << get(n) << endl;
return 0;
}