题目
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.
思路
用单调栈维护递增序列,如果当前矩形高度比栈顶大,直接入栈,如果小,一直出栈并记录出栈矩阵的宽度,宽度乘其高度更新最大值,然后入栈一个当前高度和总宽的矩形。
代码
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<bitset>
#include<set>
using namespace std;
#define _CRT_SECURE_NO_WARNINGS 1
#define ll long long
#define pub push_back
#define pob pop_back
#define pii pair<int,int>
#define pll pair<ll,ll>
#define inf 2e9
#define llf 1e18
#define endl "\n"
const ll mod = 1e6 + 7;
ll qpow(ll base, ll power)
{
ll res = 1;
while (power > 0)
{
if (power & 1) res = base * res % mod;
power >>= 1;
base = base * base % mod;
}
return res;
}
ll gcd(ll a, ll b)
{
return b == 0 ? a : gcd(b, a % b);
}
ll lcm(ll a, ll b)
{
return a / gcd(a, b) * b;
}
double dis1(double x, double y, double x1, double y1)
{
return sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1));
}
double dis2(double x, double y, double z, double x1, double y1, double z1)
{
return sqrt((x - x1) * (x - x1) + (y - y1) * (y - y1) + (z - z1) * (z - z1));
}
double chaji(double x1, double x2, double y1, double y2)
{
return x1 * y2 - x2 * y1;
}
ll n, high[100010], wide[100010], s[100010];
int main()
{
ios::sync_with_stdio(0);
cin.tie(0), cout.tie(0);
ll i, j;
while (cin >> n)
{
if (n == 0) break;
for (i = 1; i <= n; i++) cin >> high[i];
high[n + 1] = 0;//防止最后还有矩形没算
ll l = 0, ans = 0;
for (i = 1; i <= n + 1; i++)
{
if (high[i] >= s[l])
{
s[++l] = high[i];
wide[l] = 1;
}
else
{
ll w = 0;
while (s[l] > high[i])
{
w += wide[l];
ans = max(ans, w * s[l]);
l--;
}
s[++l] = high[i];
wide[l] = w + 1;
}
}
cout << ans << endl;
}
}