Bzoj 3400(单调栈)

BZOJ 3400
Luogu 2947
from: USACO 2009 Mar Sliver(USACO刷题第19题)

维护一个从顶到底单调递减的单调栈然后就可以求解了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#define ms(i, j) memset(i, j, sizeof i)
using namespace std;
const int MAXN = 100000 + 5;
int n, ans[MAXN], hi[MAXN], st[MAXN], top;
void clean() {
top = 0;
ms(st, 0);
}
void init() {
clean();
for (int i=1;i<=n;i++) scanf("%d", &hi[i]);
}
void solve() {
for (int i=n;i>=1;i--) {
while (top&&hi[i]>=hi[st[top]]) top--;
ans[i] = st[top];
st[++top] = i;
}
for (int i=1;i<=n;i++) printf("%d\n", ans[i]);
}
int main() {
#ifndef ONLINE_JUDGE
freopen("1.in", "r", stdin);freopen("1.out", "w", stdout);
#endif
while (scanf("%d", &n)==1) init(), solve();
return 0;
}
------ 本文结束 ------