单调栈

题目传送门:点击打开链接

心塞。因为一个等号找了一个上午的bug。刷题少的确是泪啊、

 
/*
题目大意:给你n头奶牛高度的数据,从左边向右边,每一头奶牛只能看到比他高度矮的奶牛。问这n头奶牛能总共看到的奶牛头数是多少
算法分析:可以构造一个单调递增栈,这样就可以求出其他奶牛看到该头奶牛的数量,求和即可 
*/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <stack>
#include <cstdlib>
using namespace std;

typedef long long int LL ;

int main() {
	int n;
	LL res, h;
	stack <LL> p;
	while (cin >> n) {
		
		while (!p.empty())
			p.pop();				//清空栈 
		res = 0;
		
		while (n --) {
			cin >> h;
			while (!p.empty() && h >= p.top())		//构造单调递增栈 
				p.pop();
			res += p.size();
			
			//cout << res<< endl;
			p.push(h);
		}
		cout << res << endl;
	}
	
	return 0;
}


原文地址:https://www.cnblogs.com/Tovi/p/6194849.html