BZOJ1660:[USACO2006NOV]Bad Hair Day

浅谈栈:https://www.cnblogs.com/AKMer/p/10278222.html

题目传送门:https://lydsy.com/JudgeOnline/problem.php?id=1660

假设(x_i)表示可以看见(i)号奶牛的数量,那么答案也可以写作(sumlimits_{i=1}^{n}x_i),然后(x_i)用单调严格下降的栈统计即可。

时间复杂度:(O(n))

空间复杂度:(O(n))

代码如下:

#include <cstdio>
using namespace std;
typedef long long ll;

const int maxn=8e4+5;

ll ans;
int n,top;
int stk[maxn];

int read() {
	int x=0,f=1;char ch=getchar();
	for(;ch<'0'||ch>'9';ch=getchar())if(ch=='-')f=-1;
	for(;ch>='0'&&ch<='9';ch=getchar())x=x*10+ch-'0';
	return x*f;
}

int main() {
	n=read();
	for(int i=1;i<=n;i++) {
		int x=read();
		while(top&&stk[top]<=x)top--;
		ans+=top;stk[++top]=x;
	}
	printf("%lld
",ans);
	return 0;
}
原文地址:https://www.cnblogs.com/AKMer/p/10279036.html