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.
题解
知识点:单调栈。
此题需要找到最邻近大于的牛,所以用单调栈维护即可。
单调栈和单调队列属于同一类原理,不同的是单调队列多了维护变区间的队头弹出,而单调栈不需要。这类单调结构除去单调队列里说过的区间最值的性质,还有一个查找最邻近大于/小于的功能,因为在元素与最邻近大于/小于之间的元素都是比自己小/大的,一定能被弹出,而之前最邻近大于/小于的元素在这之间也不会被弹出,所以新元素进入之前不被弹出的第一个元素即最邻近大于/小于的元素。
这里由于是要找右侧的,所以从右往左应用单调递减队列查找最邻近大于的元素。要注意如果栈空说明右侧没有比自己大的。
时间复杂度
空间复杂度
代码
#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; }
本文来自博客园,作者:空白菌,转载请注明原文链接:https://www.cnblogs.com/BlankYang/p/16438450.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧