单调栈,关于(Bad Hair Day)的模板题

来源:互联网 发布:港航物流软件 编辑:程序博客网 时间:2024/06/06 12:26

栈作为一种数据结构,是一种只能在一端进行插入和删除操作的特殊线性表。它按照先进后出的原则存储数据,先进入的数据被压入栈底,最后的数据在栈顶,需要读数据的时候从栈顶开始弹出数据(最后一个数据被第一个读出来)。

单调栈是一种单调递增或单调递减的栈,数据有序地储存在栈中,因此对于解决部分题目有着不错的效果。
题目如下:

Bad Hair Day
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.
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

题目意思如下:

心情不好的一天
农夫约翰的一些奶牛(数量1≤N≤80,000)有一个糟糕的一天!由于每个奶牛对于它们凌乱的发型很不自然,FJ想要数数能够看到别牛头上的奶牛的数量。
每头奶牛i都有特定的身高(身高1≤hi≤10^9)并且都面朝东边站成一线,因此,当奶牛i前面的奶牛的身高低于牛i,奶牛i都可以看到在它面前的奶牛的头的顶部。
输入
第1行:奶牛的数量N
第2..N+1行:包含一个整数,是牛i的高度
输出
第1行:一个整数,各奶牛看到奶牛数的总和
样例输入
6
10
3
7
4
12
2
样例输出
5

这一道题,我们可以用单调栈来解决。
首先,读入奶牛的数量后,因为每头奶牛都面朝东边(对题目来说,后读入高度的奶牛在东边,先读入高度的奶牛在西边)
根据题目分析,本题应当重点在于计算每个奶牛被多少奶牛所看到,而非一头奶牛看到多少头奶牛。
所以在读入奶牛高度的过程中,我们可以建立一个单调栈,读入的过程中,判断奶牛i的高度与栈顶奶牛高度的大小关系,当发现奶牛i更高时,则栈顶奶牛看不到奶牛i,删去栈顶奶牛,并且继续判断,直至栈中没有值或栈顶奶牛高于奶牛i为止,然后将奶牛i添入栈中,在此过程中,奶牛i添入栈前,栈中数据的量就是奶牛i被多少数量的奶牛看到的值,所以奶牛1..N中的此值求和,即为我们要求的各奶牛看到别牛的总数。

#include <iostream>#include <cstdio>using namespace std;long long  num=0;long long  stack[8000801];long long n,ans=0;int main(){    long long n;    scanf("%lld",&n);    for (int i=1;i<=n;i++)    {        long long j;        scanf("%lld",&j);        while ((num) and (stack[num]<=j)) num--;        ans+=num;        stack[++num]=j;    }    printf("%lld",ans);    return 0;}
原创粉丝点击