fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <stack>
  4.  
  5. using namespace std;
  6.  
  7. int main() {
  8. ios::sync_with_stdio(false);
  9. cin.tie(0);
  10.  
  11. int N;
  12. cin >> N;
  13. vector<int> H(N);
  14. for (int i = 0; i < N; ++i) {
  15. cin >> H[i];
  16. }
  17.  
  18. vector<int> result(N, 0); // 初始化为0
  19. stack<int> st; // 栈中保存的是索引
  20.  
  21. // 从右往左遍历
  22. for (int i = N - 1; i >= 0; --i) {
  23. // 弹出栈顶所有比当前元素小或等于的元素
  24. while (!st.empty() && H[st.top()] <= H[i]) {
  25. st.pop();
  26. }
  27.  
  28. if (!st.empty()) {
  29. result[i] = st.top() + 1; // 转换为1-based编号
  30. } else {
  31. result[i] = 0;
  32. }
  33.  
  34. st.push(i);
  35. }
  36.  
  37. // 输出结果
  38. for (int i = 0; i < N; ++i) {
  39. cout << result[i] << endl;
  40. }
  41.  
  42. return 0;
  43. }
  44.  
Success #stdin #stdout 0.01s 5316KB
stdin
1
2
10
42
11
stdout
0