From 24213fc267c4bab1f6c51f1ab7a64070791e0eab Mon Sep 17 00:00:00 2001 From: Baoshuo Date: Wed, 17 Jul 2024 10:39:11 +0800 Subject: [PATCH] P2947 [USACO09MAR] Look Up S https://www.luogu.com.cn/record/166555989 --- Luogu/P2947/P2947.cpp | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 Luogu/P2947/P2947.cpp diff --git a/Luogu/P2947/P2947.cpp b/Luogu/P2947/P2947.cpp new file mode 100644 index 00000000..d072ccc0 --- /dev/null +++ b/Luogu/P2947/P2947.cpp @@ -0,0 +1,37 @@ +#include +#include + +using std::cin; +using std::cout; +const char endl = '\n'; + +const int N = 1e5 + 5; + +int n, h[N], ans[N]; +std::stack st; + +int main() { + std::ios::sync_with_stdio(false); + cin.tie(nullptr); + + cin >> n; + + for (int i = 1; i <= n; i++) { + cin >> h[i]; + } + + for (int i = n; i; i--) { + // pop all elements that are smaller than h[i] + while (!st.empty() && h[i] >= h[st.top()]) st.pop(); + // if the stack is not empty, the nearest element that is larger than h[i] is st.top() + if (!st.empty()) ans[i] = st.top(); + // push h[i] into the stack + st.push(i); + } + + for (int i = 1; i <= n; i++) { + cout << ans[i] << endl; + } + + return 0; +}