AW131 直方图中最大的矩形

 

题目地址


注意点:

  • 初始化时a[n+1]应当恢复为0(多组数据).
  • width[top]每次都应当设为nowWidth+1.

#include<cstdio>
#include<iostream>
#define ll long long
using namespace std;
const int MAXN=3e5;
int top=0;
int width[MAXN],height[MAXN];
void init(){
	top=0;
}
int a[MAXN];
int main(){
	while(1){
		init();
		int n;
		scanf("%d",&n);
		if(n==0)break;
		for(int i=1;i<=n;i++){
			scanf("%d",&a[i]);
		}
		a[n+1]=0;
		ll ans=0;
		for(int i=1;i<=n+1;i++){
			if(a[i]>=height[top]){
				height[++top]=a[i];
				width[top]=1;
			}else{
				int nowWidth=0;
				while(height[top]>a[i]){
					nowWidth+=width[top];
					ans=max(ans,(ll)height[top]*nowWidth);
					top--;
				}
				width[++top]=nowWidth+1;
				height[top]=a[i];
			}
		}
		cout<<ans<<endl;
	}
	return 0;
}

  

猜你喜欢

转载自www.cnblogs.com/zbsy-wwx/p/11740674.html
今日推荐