ACM PKU 2082 Terrible Sets http://acm.pku.edu.cn/JudgeOnline/problem?id=2082
|
这是一道关于最大覆盖的问题,对于这种问题,用一个双向DP足以解决问题,双向DP在以前的文章中已经有使用过,但是我这次挑战了用堆栈做的,思路跟DP一样的,只是操作简单了罢了。时效也应该比DP强。 思维误区: 我不知道每次大于栈顶的元素是否要判定它的值与最大面积MAX_area之间的关系,所以对它的判断我在压栈时就开始了,多余了.....
#include <iostream>
#include <stack>
using namespace std;
#define MAX_SIZE 50001
struct node{
int w,h;
}rec[MAX_SIZE];
int main()
{
int n;
__int64 temp,MAX_area;
int total_w=0;
stack <node> mystack;
while (scanf("%d",&n) && n!=-1)
{
int i = 0;
for(; i < n; i++)
{
scanf("%d%d",&rec[i].w,&rec[i].h);
}
mystack.push(rec[0]);
MAX_area = 0;
for(i = 1;i < n; i++)
{
if(mystack.top().h<=rec[i].h)
{
mystack.push(rec[i]);
continue;
}
else
{
while (!mystack.empty() && mystack.top().h >= rec[i].h)
{
total_w += mystack.top().w;
temp = mystack.top().h * total_w;
MAX_area = temp > MAX_area ? temp : MAX_area;
mystack.pop();
}
node rect;
rect.h = rec[i].h;
rect.w = total_w + rec[i].w;
mystack.push(rect);
total_w = 0;
}
}
while(!mystack.empty())
{
total_w += mystack.top().w;
if((temp = total_w * mystack.top().h) > MAX_area)
MAX_area = temp;
mystack.pop();
}
total_w=0;
printf("%I64d\n",MAX_area);
MAX_area = 0;
}
return 0;
}
此题最关键的部分是对mystack.top().h>rec[i].h的情况的判断,一定要细心,慎重;此时出现的情况一定要把握全局,自己画图就知道其中的道理了...不多说....
最后,结束时要注意的是栈是否为空,这个也影响到最优结果的获得.....代码很简单,我只是尝试了用不同的方法做了一下,要注意的地方就是两点: 1、要把握整体状态转移规律 2、要细心
|
浙公网安备 33010602011771号