CodeForces 280B Maximum Xor Secondary 單調棧

這道題思路真的不好想呀。。看了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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章