icpc:problems:luogup2866
目录
problems | |
---|---|
名称 | Bad Hair Day |
题目编号 | P2866 |
题目链接 | luogu.com.cn/… |
来源 | USACO |
算法分类 | 栈, 单调栈 |
难易程度 | 容易 |
Bad Hair Day
想法
维护一个单调递减的栈。
加入一个新元素:第i头牛。检查栈顶与第i个牛:
- 第i个牛比栈顶要矮,栈顶的牛也能看到第i头牛。
- 第i头牛比栈顶要高,栈顶的牛是看不到后续的牛了。栈顶的牛看到的范围:栈顶到i。
- 第i头牛入栈。
最后如果栈还存在元素,依次出栈,说明这些牛,都能看到第N头牛,统计答案。
代码实现
#include<cstdio> const int N = 1e4*8; int sta[N], line[N], top, n; long long int ans = 0; int main() { scanf("%d", &n); for(int i=1; i<=n; i++) scanf("%d", &line[i]); for(int i=1; i<=n; i++) { while(top > 0 && line[sta[top]] <= line[i]) { ans += (i-sta[top]-1); top--; } sta[++top] = i; } while(top > 0) { ans += (n-sta[top]); top--; } printf("%lld", ans); return 0; }
/app/www/public/data/pages/icpc/problems/luogup2866.txt · 最后更改: 2024/01/31 11:55 由 温婕莺