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

时间:2023-03-09 17:33:16
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:

 #include <iostream>
#include <stdio.h>
#include <string.h>
#include <stack>
#define MAX_N 80005
#define INF_LL 100000000000000000LL using namespace std; int n;
long long ans=;
long long h[MAX_N];
stack<int> stk; void read()
{
cin>>n;
for(int i=;i<n;i++)
{
cin>>h[i];
}
} void solve()
{
h[n]=INF_LL;
for(int i=;i<=n;i++)
{
while(!stk.empty() && h[stk.top()]<=h[i])
{
ans+=i-stk.top()-;
stk.pop();
}
stk.push(i);
}
} void print()
{
cout<<ans<<endl;
} int main()
{
read();
solve();
print();
}