poj 2082 Terrible Sets (单调栈)

来源:互联网 发布:知乎提示浏览器版本低 编辑:程序博客网 时间:2024/04/30 09:19
Terrible Sets
Time Limit: 1000MS Memory Limit: 30000KTotal Submissions:5258 Accepted: 2666

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 w1h1+w2h2+...+wnhn < 109.

Output

Simply output Max(S) in a single line for each case.


为什么要将它转化成单调递增的形式。

当一个比较高的方块 要往两边延伸的时候形成新的方块的高度往往受限与新方块的高度。

也就是说当我们插入了一个比较矮的方块的时候。

我们之前高的方块无法跨过它直接往后边蔓延。

所以高度也就会被同化掉。

同理向前延伸的时候也是这样。

假设新插入的高度为 h 宽度为w 的方块 i

在 i 前 高度高度于 h 的块倘若要延伸到 i 的位置那么它的高度都会被同化。

我们需要遍历的时候产生新的块进行插入///详细操作请看代码输入的时候 while(!s.empty()&&s.top().h>=h)

所以我们可以将这个数列转化成单调递增的形式。///至于为什么转化成单调递增的形式,前边的那几行主要讲的就是这个

最后我们需要从后往前遍历 从后往前遍历的时候因为高度再变低但是所以每次高度继承当前节点的高度。

宽度是到当前节点的总和。


#include<stdio.h>#include<string.h>#include<stack>#include<string.h>#include<queue>#include<algorithm>using namespace std;struct Rectangle{    int w,h;    Rectangle(int x,int y)    {        w=x;        h=y;    }};stack<Rectangle>s;int main(){    int n;    while(~scanf("%d",&n))    {        if(n==-1)break;        int res=0;        while(!s.empty())s.pop();        for(int i=0; i<n; i++)        {            int w,h,Tmpw,Tmph;            scanf("%d%d",&w,&h);            Tmpw = 0;            while(!s.empty()&&s.top().h>=h)            {                Tmpw += s.top().w;                Tmph = s.top().h;                int Tmps =  Tmpw * Tmph;                res = max(res,Tmps);                s.pop();            }            s.push(Rectangle(Tmpw+w,h));        }        int H=0,W=0;        while(!s.empty())        {            W += s.top().w;            H = s.top().h;            res = max(res, W*H);            s.pop();        }        printf("%d\n",res);    }}



原创粉丝点击