BZOJ 1660 [Usaco2006 Nov]Bad Hair Day 乱发节:单调栈

题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=1660

题意:

  有n头牛,身高分别为h[i]。

  它们排成一排,面向右边。第i头牛可以看见在它右边的牛j,只要h[i] > h[j],且中间没有身高 >= h[i]的牛挡住视线。

  第i头牛能看见c[i]只别的牛。

  问你 ∑ c[i]为多少。

题解:

  单调栈。

  

  单调性:

    栈内存牛的编号。

    从栈底到栈顶,h[i]单调递减。

  

  从左到右枚举每头牛。

  如果枚举到第i头牛时,栈内的某头牛k满足h[i] >= h[k],被弹出,则k的视野的最右端为i-1。

  所以c[k] = k-i-1。即:ans += k-i-1。

AC Code:

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <string.h>
 4 #include <stack>
 5 #define MAX_N 80005
 6 #define INF_LL 100000000000000000LL
 7 
 8 using namespace std;
 9 
10 int n;
11 long long ans=0;
12 long long h[MAX_N];
13 stack<int> stk;
14 
15 void read()
16 {
17     cin>>n;
18     for(int i=0;i<n;i++)
19     {
20         cin>>h[i];
21     }
22 }
23 
24 void solve()
25 {
26     h[n]=INF_LL;
27     for(int i=0;i<=n;i++)
28     {
29         while(!stk.empty() && h[stk.top()]<=h[i])
30         {
31             ans+=i-stk.top()-1;
32             stk.pop();
33         }
34         stk.push(i);
35     }
36 }
37 
38 void print()
39 {
40     cout<<ans<<endl;
41 }
42 
43 int main()
44 {
45     read();
46     solve();
47     print();
48 }
原文地址:https://www.cnblogs.com/Leohh/p/7636228.html