NC24840 [USACO 2009 Mar S]Look Up

题目

题目描述

Farmer John's N (1 <= N <= 100,000) cows, conveniently numbered 1..N, are once again standing in a row. Cow i has height Hi (1 <= Hi <= 1,000,000).
Each cow is looking to her left toward those with higher index numbers. We say that cow i 'looks up' to cow j if i < j and Hi < Hj. For each cow i, FJ would like to know the index of the first cow in line looked up to by cow i.
Note: about 50% of the test data will have N <= 1,000.

输入描述

  • Line 1: A single integer: N
  • Lines 2..N+1: Line i+1 contains the single integer: Hi

输出描述

  • Lines 1..N: Line i contains a single integer representing the smallest index of a cow up to which cow i looks. If no such cow exists, print 0.

示例1

输入

6
3
2
6
1
1
2

输出

3
3
0
6
6
0

说明

FJ has six cows of heights 3, 2, 6, 1, 1, and 2.
Cows 1 and 2 both look up to cow 3; cows 4 and 5 both look up to cow 6; and cows 3 and 6 do not look up to any cow.

题解

知识点:单调栈。

此题需要找到最邻近大于的牛,所以用单调栈维护即可。

单调栈和单调队列属于同一类原理,不同的是单调队列多了维护变区间的队头弹出,而单调栈不需要。这类单调结构除去单调队列里说过的区间最值的性质,还有一个查找最邻近大于/小于的功能,因为在元素与最邻近大于/小于之间的元素都是比自己小/大的,一定能被弹出,而之前最邻近大于/小于的元素在这之间也不会被弹出,所以新元素进入之前不被弹出的第一个元素即最邻近大于/小于的元素。

这里由于是要找右侧的,所以从右往左应用单调递减队列查找最邻近大于的元素。要注意如果栈空说明右侧没有比自己大的。

时间复杂度 O(n)

空间复杂度 O(n)

代码

#include <bits/stdc++.h>
using namespace std;
int h[100007];
int main() {
std::ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int n;
cin >> n;
for (int i = 1;i <= n;i++) cin >> h[i];
stack<int> q;
vector<int> ans;
for (int i = n;i >= 1;i--) {
while (!q.empty() && h[q.top()] <= h[i]) q.pop();
ans.push_back(q.empty() ? 0 : q.top());
q.push(i);
}
for (int i = n - 1;i >= 0;i--) cout << ans[i] << '\n';
return 0;
}
posted @   空白菌  阅读(36)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
点击右上角即可分享
微信分享提示