洛谷P1823 音乐会的等待 单调栈

洛谷P1823 音乐会的等待
单调栈
维护一个上升的单调栈
用以记录有当前这个数向后能看到几个数
但是每次加入一个数 时 他能看到的 是
单调栈中所有比他小的 和跟他一样的数
比他小的下次就没有用了,所以直接退栈
但是 相同的数到后面还是可能会有贡献的,所以贡献算完以后
又要进栈
最后如果栈中还有元素,那么栈顶一定能看到自身,所以+1

 

 1 #include <bits/stdc++.h> 
 2 #define For(i,j,k) for(int i=j;i<=k;i++) 
 3 #define LL long long
 4 using namespace std ; 
 5 
 6 const int N = 500011 ; 
 7 int n,x,top,t ; 
 8 int st[N] ;
 9 LL sum ;  
10 
11 inline int read() 
12 {
13     int x = 0 , f = 1 ; 
14     char ch = getchar() ; 
15     while(ch<'0'||ch>'9') { if(ch=='-') f = -1 ; ch = getchar(); } 
16     while(ch>='0'&&ch<='9') { x = x * 10+ch-48 ; ch = getchar(); } 
17     return x * f ; 
18 }
19 
20 int main() 
21 {
22     n = read() ; 
23     For(i,1,n) {
24         x = read() ; 
25         t = 1 ; // 记录有几个数与 x 相同 包括自身 
26         while(top>0&&st[ top ] <= x ) {
27             if(st[top] == x ) t++ ;  
28             top-- ; sum++ ; 
29         } 
30         if( top>0 ) sum++ ; 
31         For(j,1,t) st[++top] = x ; 
32     }
33     printf("%lld",sum) ; 
34     return 0 ; 
35 }

 

posted @ 2017-07-22 09:20  third2333  阅读(400)  评论(0编辑  收藏  举报