CodeForces 280B Maximum Xor Secondary 单调栈

血红的双手。 提交于 2019-11-29 07:26:55

这道题思路真的不好想呀。。看了Leaderboard,发现大佬们的代码如此简练Orz

怎么想出来的我就不晓得了,模拟一下他们的过程加深理解吧。。以样例中的5 2 1 4 3为例:

stack:5   a[i]:2   ans=5^2

stack:5 2   a[i]:1   1<2, ans=1^2(对应序列[2,1]的最大次大值,[5,2,1]相当于[5,2],因此此时2不出栈,构成单调递减栈)

stack:5 2 1   a[i]:4   4>1, ans=4^1( [1,4] ), 1出栈;4>2, ans=4^2( [2,1,4] ), 2出栈;4<5, ans=4^5( [5,2,1,4] )

stack:5 4   a[i]:3   3<4, ans=3^4( [4,3] )

这样模拟之后就会发现把所有可能的情况都算了一遍,从中挑选最大值。附上AC代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<stack>
using namespace std;
const int INF=0x3f3f3f3f;
const int MAX=1e5+5;
int n,a[MAX];
stack<int>st;
int main()
{
    while(scanf("%d",&n)==1)
    {
        for(int i=1;i<=n;i++)
            scanf("%d",&a[i]);
        while(!st.empty())
            st.pop();
        st.push(a[1]);
        int ans=0;
        for(int i=2;i<=n;i++)
        {
            while(!st.empty()&&st.top()<a[i])
            {
                ans=max(ans,st.top()^a[i]);
                st.pop();
            }
            if(!st.empty())
                ans=max(ans,st.top()^a[i]);
            st.push(a[i]);
        }
        printf("%d\n",ans);
    }
	return 0;
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!