POJ2082 terrible set妈妈再也不用担心我不会用stack了

Terrible Sets POJ2082

题目地址:http://poj.org/problem?id=2082

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.
Sample Input
3
1 2
3 4
1 2
3
3 4
1 2
3 4
-1
Sample Output
12
14

昨天看了余老师书上写的,看了半个小时,总觉得哪里不对,发现是题意看错了,我以为矩形可以变位置,去吃了个早饭,突然就想通了,明苑二楼的早饭挺好吃的!!就当练习一下容器吧。
题意就是长宽不同的矩形们固定好了放在一起,在这个不规则的图形里面找出一个最大的矩形。
用堆栈来做,把高度升序的作为一个小组块,把他们压到栈里去,则得到这个小组块的最大宽,乘上这个小组块的最小高度。这个用stack来写很合
模拟的图
计算顺序是:
按升序入栈,如果不是升序被打断了,则开始记录前一个升序组块的Smax

s1=h3w3;//记录下宽度totalw=w3,h3矩形出栈;
s2=h2
(w2+w3)//宽度totalw=w3+w2,h2矩形出栈;
s3=h1*(w1+w2+w3)//totalw=w1+w2+w3,h1矩形出栈;
计算期间记录下Smax;

下一个矩形是h4,w4;
h4小于h3,不满足升序,计算过上一个组块的最大面积之后,现在栈里是空的(s.empty())
然后将一个长度为(totalw+w4),高度为h4的矩形压入,再压入h5,w5的矩形,如果升序,则重复刚才升序组块计算Smax的操作;
最后求得最大值。

代码如下(自己尝试着默写余老师书上的代码)

#include<iosteam>
#include<stdio>
#include<stack>
using namespace std;
struct rec{
 int w;
 int h;
}data;
int main()
{	
	int n;
	int lasth=0;
	struct s;
	while(scanf("%d",&n)&&n!=-1){
		while(n--){
			scanf("%d %d",&data.w,&data.h);
			if(data.h>=lasth)
			s.push(data);
			else
			{
				int totalw=0;
				int s1,smax=0;
				while(!s.top.empty()){
					totalw+=data.w;
					s1=totalw*data.h;
					if(s1>smax)
					smax=s1;
					s.pop();
				}
				totalw+=data.w;
				data.w=totalw;
				s.push(data);
			}
			lasth=data.h;
		}
		int totalw=0;
				int s1,smax=0;
				while(!s.top.empty()){
					totalw+=data.w;
					s1=totalw*data.h;
					if(s1>smax)
					smax=s1;
					s.pop();
				}
		printf("%d",&smax);
		return 0;	
}


猜你喜欢

转载自blog.csdn.net/qq_43545958/article/details/86286186