Terrible Sets
http://poj.org/problem?id=2082
Time Limit: 1000MS |
|
Memory Limit: 30000K |
|
|
|
Description
Let N be the set of all natural numbers {0 , 1 , 2 , . . . }, and R be the set of all real numbers. wi, hi for i = 1 . . . n are some elements in N, and w0 = 0.
Define set B = {< x, y > | x, y ∈ R and there exists an index i > 0 such that 0 <= y <= hi ,∑
0<=j<=i-1wj <= x <= ∑
0<=j<=iwj}
Again, define set S = {A| A = WH for some W , H ∈ R
+ and there exists x0, y0 in N such that the set T = { < x , y > | x, y ∈ R and x0 <= x <= x0 +W and y0 <= y <= y0 + H} is contained in set B}.
Your mission now. What is Max(S)?
Wow, it looks like a terrible problem. Problems that appear to be terrible are sometimes actually easy.
But for this one, believe me, it's difficult.
Input
The input consists of several test cases. For each case, n is given in a single line, and then followed by n lines, each containing wi and hi separated by a single space. The last line of the input is an single integer -1, indicating the end of input. You may assume that 1 <= n <= 50000 and w
1h
1+w
2h
2+...+w
nh
n < 10
9.
Output
Simply output Max(S) in a single line for each case.
Sample Input
3
1 2
3 4
1 2
3
3 4
1 2
3 4
-1
Sample Output
12
14
题目大意:给定n个相邻的矩形,宽和高分别为w,h,求这些矩形能构成的矩形的最大面积?
今天知道有单调栈这种数据结构
用单调递增栈很容易就能求出以h[i]为最小值的区间
大致过程如下:
若h[i]<s[top].h,则不停弹出栈顶元素,直至h[i]>=s[top].h,且此h[i]的起始位置为弹出的最后一个元素的起始位置;
否则直接进栈,其起始位置为i
#include <cstdio>
#include <algorithm>
using namespace std;
int n,w,h[50005],top,oriTop;
long long sumW[50005],ans;//sumW[i]表示w在区间[1,i]上的和
struct Node {
int h,sta;//sta表示高度h的起始下标
}s[50005];
int main() {
while(scanf("%d",&n),n!=-1) {
sumW[0]=0;
for(int i=1;i<=n;++i) {
scanf("%d%d",&w,h+i);
sumW[i]=sumW[i-1]+w;
}
h[++n]=-1;//令最后一个元素的下一个高度为-1,避免循环完毕后还要弹出栈中所有元素
s[0].h=-1;
s[0].sta=top=0;
ans=0;
for(int i=1;i<=n;++i) {
oriTop=top;
while(h[i]<s[top].h) {
ans=max(ans,(sumW[i-1]-sumW[s[top].sta-1])*s[top].h);
--top;//弹出栈顶元素
}
s[++top].h=h[i];
if(oriTop<top)//如果没有元素弹出,则其起始下标就是自己的下标,否则其起始下标是弹出的最后一个元素的起始下标
s[top].sta=i;
}
printf("%I64d\n",ans);
}
return 0;
}