51nod1423 最大二"货" 单调栈

枚举每个点作为次大值,用单调栈处理出左边 / 右边第一个比它大的数,直接回答

复杂度$O(n)$

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;

extern inline char gc() {
    static char RR[23456], *S = RR + 23333, *T = RR + 23333;
    if(S == T) fread(RR, 1, 23333, stdin), S = RR;
    return *S ++;
}
inline int read() {
    int p = 0, w = 1; char c = gc();
    while(c > '9' || c < '0') { if(c == '-') w = -1; c = gc(); }
    while(c >= '0' && c <= '9') p = p * 10 + c - '0', c = gc();
    return p * w;
}

#define sid 200050
#define ri register int

int n, top, ans;
int st[sid], s[sid], L[sid], R[sid];

int main() {
    n = read();
    for(ri i = 1; i <= n; i ++) s[i] = read();
    
    
    st[top = 1] = 0; s[0] = 1e9 + 5;
    for(ri i = 1; i <= n; i ++) {
        while(top && s[st[top]] <= s[i]) top --;
        L[i] = st[top]; st[++ top] = i;
    }

    st[top = 1] = n + 1; s[n + 1] = 1e9 + 5;
    for(ri i = n; i >= 1; i --) {
        while(top && s[st[top]] <= s[i]) top --;
        R[i] = st[top]; st[++ top] = i;
    }

    for(ri i = 1; i <= n; i ++) {
        if(L[i] != 0) ans = max(ans, s[i] ^ s[L[i]]);
        if(R[i] != n + 1) ans = max(ans, s[i] ^ s[R[i]]);
    }

    printf("%d\n", ans);
    return 0;
}

 

posted @ 2018-08-30 07:36  remoon  阅读(175)  评论(0编辑  收藏  举报