【代码超详解】POJ 3250 Bad Hair Day(单调栈,219 ms)

一、题目描述

Bad Hair Day

Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 27077 Accepted: 9287(2020/2/5 23:27)

Description

Some of Farmer John’s N cows (1 ≤ N ≤ 80,000) are having a bad hair day! Since each cow is self-conscious about her messy hairstyle, FJ wants to count the number of other cows that can see the top of other cows’ heads.

Each cow i has a specified height hi (1 ≤ hi ≤ 1,000,000,000) and is standing in a line of cows all facing east (to the right in our diagrams). Therefore, cow i can see the tops of the heads of cows in front of her (namely cows i+1, i+2, and so on), for as long as these cows are strictly shorter than cow i.

Consider this example:

在这里插入图片描述

Cow#1 can see the hairstyle of cows #2, 3, 4
Cow#2 can see no cow’s hairstyle
Cow#3 can see the hairstyle of cow #4
Cow#4 can see no cow’s hairstyle
Cow#5 can see the hairstyle of cow 6
Cow#6 can see no cows at all!

Let ci denote the number of cows whose hairstyle is visible from cow i; please compute the sum of c1 through cN.For this example, the desired is answer 3 + 0 + 1 + 0 + 1 + 0 = 5.

Input

Line 1: The number of cows, N.
Lines 2…N+1: Line i+1 contains a single integer that is the height of cow i.

Output

Line 1: A single integer that is the sum of c1 through cN.

Sample Input

6
10
3
7
4
12
2

Sample Output

5

Source

USACO 2006 November Silver

二、算法分析说明与代码编写指导

单调栈板子题。
按从西往东的顺序把牛的高度压入栈。栈从顶向底是递增的。
待插入的元素比栈顶元素大时,一直弹出直到栈为空或栈顶大于待插入元素。
这一步模拟表示:栈中剩下的元素对应的每一头牛(较高)都能看到准备入栈的这一头牛(较矮)。
所以,总和在插入之前要加上当前的栈大小。
全部牛的高度都压入栈后,输出总和。

扫描二维码关注公众号,回复: 8996841 查看本文章

三、AC 代码(219 ms)

#include<cstdio>
#include<stack>
#pragma warning(disable:4996)
using namespace std;
unsigned long long a, h[80000]; unsigned n; stack<unsigned long long> s;
int main() {
	scanf("%u", &n);
	for (unsigned i = 0; i < n; ++i)scanf("%llu", &h[i]);
	s.push(h[0]);
	for (unsigned i = 1; i < n; ++i) {
		while (s.empty() == false && s.top() <= h[i])s.pop();
		a += s.size(); s.push(h[i]);
	}
	printf("%llu\n", a);
	return 0;
}
发布了214 篇原创文章 · 获赞 19 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/COFACTOR/article/details/104190323