Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 22186 | Accepted: 7178 |
Description
Usually, histograms are used to represent discrete distributions, e.g., the frequencies of characters in texts. Note that the order of the rectangles, i.e., their heights, is important. Calculate the area of the largest rectangle in a histogram that is aligned at the common base line, too. The figure on the right shows the largest aligned rectangle for the depicted histogram.
Input
Output
Sample Input
7 2 1 4 5 1 3 3 4 1000 1000 1000 1000 0
Sample Output
8 4000
Hint
Source
#include<stdio.h>
#include<stack>
using namespace std;
struct s{
long long x;
long long l;
long long r;
}a[100010];
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
if(n==0)
return 0;
for(int i=0;i<n;i++)
{
scanf("%lld",&a[i].x);
a[i].l=i;
a[i].r=i;
}
stack<s>q;
for(int i=0;i<n;i++) //確定左端點
{
if(q.empty())
{
q.push(a[i]);
}
else
{
if(q.top().x<a[i].x)
{
q.push(a[i]);
}
else
{
while(q.top().x>=a[i].x)
{
a[i].l=q.top().l;
q.pop();
if(q.empty())
{
break;
}
}
q.push(a[i]);
}
}
}
while(!q.empty())
{
q.pop();
}
for(int i=n-1;i>=0;i--) //確定右端點
{
if(q.empty())
{
q.push(a[i]);
}
else
{
if(q.top().x<a[i].x)
{
q.push(a[i]);
}
else
{
while(q.top().x>=a[i].x)
{
a[i].r=q.top().r;
q.pop();
if(q.empty())
{
break;
}
}
q.push(a[i]);
}
}
}
long long ans;
long long max_=0;
for(int i=0;i<n;i++)
{
ans=(long long)((a[i].r-a[i].l+1)*a[i].x);
if(max_<ans)
{
max_=ans;
}
}
printf("%lld\n",max_);
}
}