# POJ 2559 Largest Rectangle in a Histogram

Description

A histogram is a polygon composed of a sequence of rectangles aligned at a common base line. The rectangles have equal widths but may have different heights. For example, the figure on the left shows the histogram that consists of rectangles with the heights 2, 1, 4, 5, 1, 3, 3, measured in units where 1 is the width of the rectangles:

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

The input contains several test cases. Each test case describes a histogram and starts with an integer n, denoting the number of rectangles it is composed of. You may assume that 1<=n<=100000. Then follow n integers h1,...,hn, where 0<=hi<=1000000000. These numbers denote the heights of the rectangles of the histogram in left-to-right order. The width of each rectangle is 1. A zero follows the input for the last test case.

Output

For each test case output on a single line the area of the largest rectangle in the specified histogram. Remember that this rectangle must be aligned at the common base line.

Sample Input

7 2 1 4 5 1 3 3
4 1000 1000 1000 1000
0


Sample Output

8
4000


Hint

Huge input, scanf is recommended.

#include<set>
#include<map>
#include<ctime>
#include<cmath>
#include<stack>
#include<queue>
#include<bitset>
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<functional>
#define rep(i,j,k) for (int i = j; i <= k; i++)
#define per(i,j,k) for (int i = j; i >= k; i--)
#define loop(i,j,k) for (int i = j;i != -1; i = k[i])
#define lson x << 1, l, mid
#define rson x << 1 | 1, mid + 1, r
#define fi first
#define se second
#define mp(i,j) make_pair(i,j)
#define pii pair<string,string>
using namespace std;
typedef long long LL;
const int low(int x) { return x&-x; }
const double eps = 1e-8;
const int INF = 0x7FFFFFFF;
const int mod = 1e8;
const int N = 3e5 + 10;
{
char ch = getchar();
while (ch<'0' || ch>'9') ch = getchar();
int x = ch - '0';
while ((ch = getchar()) >= '0'&&ch <= '9') x = x * 10 + ch - '0';
return x;
}
int n, a[N], l[N], r[N];

int main()
{
while (n = read(), n)
{
rep(i, 1, n) scanf("%d", &a[i]);
stack<int> p;
a[0] = a[n + 1] = -1;
rep(i, 1, n + 1)
{
while (!p.empty() && a[i] < a[p.top()]) r[p.top()] = i - 1, p.pop();
p.push(i);
}
per(i, n, 0)
{
while (!p.empty() && a[i] < a[p.top()]) l[p.top()] = i + 1, p.pop();
p.push(i);
}
LL ans = 0;
rep(i, 1, n) ans = max(ans, 1LL * a[i] * (r[i] - l[i] + 1));
printf("%lld\n", ans);
}
return 0;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：POJ 2559 Largest Rectangle in a Histogram 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)