用单调栈计算出一个数字, 左边第一个比他小的数字的位置, 右边比第一个他小的数字的位置, 然后len = r[i] - l[i] +1. ans[len] = max(ans[len], a[i])
1 #include<bits/stdc++.h> 2 using namespace std; 3 const int maxn = 2e5+5; 4 int l[maxn], r[maxn], ans[maxn], a[maxn], q[maxn]; 5 int main() 6 { 7 int n; 8 cin>>n; 9 for(int i = 1; i<=n; i++) { 10 scanf("%d", &a[i]); 11 } 12 int i = 1, st = 0; 13 while(i<=n) { 14 while(st&&a[q[st-1]]>a[i]) { 15 r[q[st-1]] = i-1; 16 st--; 17 } 18 q[st++] = i; 19 i++; 20 } 21 while(st) { 22 r[q[st-1]] = n; 23 st--; 24 } 25 i = n; 26 while(i>=1) { 27 while(st&&a[q[st-1]]>a[i]) { 28 l[q[st-1]] = i+1; 29 st--; 30 } 31 q[st++] = i; 32 i--; 33 } 34 while(st) { 35 l[q[st-1]] = 1; 36 st--; 37 } 38 memset(ans, 0, sizeof(ans)); 39 for(int i = 1; i<=n; i++) { 40 int len = r[i]-l[i]+1; 41 if(ans[len]<a[i]) { 42 ans[len] = a[i]; 43 } 44 } 45 for(i = n; i>=1; i--) { 46 if(ans[i]>=ans[i-1]) 47 ans[i-1] = ans[i]; 48 } 49 for(int i = 1; i<=n; i++) { 50 printf("%d ", ans[i]); 51 } 52 }
codeforces 547B. Mike and Feet 单调栈
原文:http://www.cnblogs.com/yohaha/p/5022589.html