2 solutions
-
5
单调栈用于维护一个区间,栈内的元素是有序的(“序”可以自定义,不一定是从小到大)
代码
#include <bits/stdc++.h> using namespace std; const int N = 3000005; int a[N]; int s[N],top; int ans[N],h[N]; bool cmp(int b,int c){ return b > c; } int main(int argc, char **argv){ int n; cin >> n; for (int i = 1;i <= n;i++){ cin >> a[i]; } for (int i = n;i > 0;i--){ // 从后往前找,因为是找第 i 个元素后面的数 // 从大到小排,记得重写规则 top = lower_bound(s,s + top,a[i],cmp) - s; // s[top] 是不合法的,s[top-1] 才是合法的 ans[i] = h[top - 1]; s[top] = a[i]; h[top++] = i; } for (int i = 1;i <= n;i++){ printf("%d ",ans[i]); } return 0; }
- 1
Information
- ID
- 4622
- Time
- 1000ms
- Memory
- 125MiB
- Difficulty
- 3
- Tags
- # Submissions
- 67
- Accepted
- 17
- Uploaded By