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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值