單調棧模板題

題意

N個人正在排隊進入一個音樂會。人們等得很無聊,於是他們開始轉來轉去,想在隊伍裏尋找自己的熟人。隊列中任意兩個人A和B,如果他們是相鄰或他們之間沒有人比A或B高,那麼他們是可以互相看得見的。

寫一個程序計算出有多少對人可以互相看見。


解析

維護一個不升的序列(單調棧…?)


#include <cstdio>
#include <algorithm>

#define Rep( i , _begin , _end ) for(int i=(_begin),i##_END = (_end);i<=i##_END;i++)
#define For( i , _begin , _end ) for(int i=(_begin),i##_END = (_end);i!=i##_END;i++)
#define Lop( i , _begin , _end ) for(int i=(_begin),i##_END = (_end);i>=i##_END;i--)
#define Dnt( i , _begin , _end ) for(int i=(_begin),i##_END = (_end);i!=i##_END;i--)

using std :: max;
using std :: min;
using std :: sort;

const int maxx = 500000 + 25;

int a[maxx],d[maxx];
int n,m,x,y,z,ans,top,cnt;

int main(){
    scanf("%d",&n);
    Rep( i , 1 , n ) scanf("%d",&a[i]);
    Rep( i , 1 , n ){
        int tmp = top;
        while(a[i] >= d[tmp] && tmp){
            ans ++;
            tmp --;
        }
        if(tmp) ans ++;
        while(top && d[top] < a[i]) top --;
        top ++;
        d[top] = a[i];
    }
    printf("%d\n",ans);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章