POJ 2082 Terrible Sets 单调栈的应用

来源:互联网 发布:mac os系统目录 编辑:程序博客网 时间:2024/05/16 14:21

题目条件叙述挺恶心的,其实表达意思挺简单的。就是给你几个矩形(依次在x轴上排开),问你能够组成的最大矩形面积。

本题采用一个栈作为存储数据结构,当前读入的矩形的高度如果大于栈顶矩形的高度的话直接进栈,否则依次出栈计算跟新最大面积,直到某一刻栈顶的高度小于当前读入的矩形的高度,进栈,这样把所以矩形都读入后在扫一遍栈跟新最大面积即可。

#include<stdio.h>#include<stdlib.h>#include<algorithm>#include<string.h>using namespace std; struct point{int h;int w;}stack[50005];int main(){int n,i,curw,curh;while(scanf("%d",&n) && n!=-1){int lasth=0,top=0,ans=0;for(i=1;i<=n;i++){scanf("%d %d",&curw,&curh);if(curh>=lasth){stack[top].h=curh;stack[top++].w=curw;}else{int totw=0;while(top>0){if(stack[top-1].h>curh){if((totw+stack[top-1].w)*stack[top-1].h>ans)ans=(totw+stack[top-1].w)*stack[top-1].h;totw+=stack[top-1].w;top--;}elsebreak;}stack[top].h=curh;stack[top++].w=totw+curw;}lasth=stack[top-1].h;}int totw=0;while(top>0){if((totw+stack[top-1].w)*stack[top-1].h>ans)ans=(totw+stack[top-1].w)*stack[top-1].h;totw+=stack[top-1].w;top--;}printf("%d\n",ans);}}