Largest Rectangle in a Histogram /// 单调栈 oj23906
题目大意:
输入n,,1 ≤ n ≤ 100000,接下来n个数为每列的高度h ,0 ≤ hi ≤ 1000000000
求得最大矩阵的面积
Sample Input
7 2 1 4 5 1 3 3
4 1000 1000 1000 1000
0
Sample Output
8
4000
#include <bits/stdc++.h> #define ll long long using namespace std; ll n,a[100005],L[100005],R[100005],sta[100005]; // sta[]模拟栈 int main() { while(~scanf("%lld",&n)) { if(n==0) break; for(int i=0;i<n;i++) scanf("%lld",&a[i]); int tail=0; for(int i=0;i<n;i++) { while(tail>0 && a[sta[tail-1]]>=a[i]) tail--; L[i]= tail==0 ? 0:sta[tail-1]+1; sta[tail++]=i; } /// L[]存放向左能达到的最远下标 // for(int i=0;i<n;i++) printf("%lld ",L[i]);printf("\n"); tail=0; for(int i=n-1;i>=0;i--) { while(tail>0 && a[sta[tail-1]]>=a[i]) tail--; R[i]= tail==0 ? n:sta[tail-1]; sta[tail++]=i; } /// R[]存放向右能达到的最远下标+1 // for(int i=0;i<n;i++) printf("%lld ",R[i]);printf("\n"); ll ans=0; for(int i=0;i<n;i++) ans=max(ans,a[i]*(R[i]-L[i])); /// R[i]-L[i]就能得到该矩阵的长度 printf("%lld\n",ans); } return 0; }