zoukankan      html  css  js  c++  java
  • POJ Largest Rectangle in a Histogram

    POJ2559

    这道题可以说是单调栈求矩形最大面积的板子题了啊

    Code:

     1 #include <cstdio>
     2 #define ll long long
     3 using namespace std;
     4 const int N = 1e5 + 7;
     5 int n, height, top;
     6 ll ans, tot, tmp;
     7 struct node{
     8     int h, num;
     9     //h存当前矩形高度
    10     //num存当前矩形左侧比自己高的矩形个数, 也就是以当前的矩形高为高的矩形的宽度 
    11 }stk[N];
    12 int main () {
    13     while (~scanf("%d", &n) && n) {
    14         top = ans = 0;
    15         for (int i = 0; i < n; i++) {
    16             scanf("%d", &height);
    17             tmp = 0;
    18             while (top > 0 && stk[top].h >= height) {//比新加进的矩形高的矩形先出栈 
    19                 tot = stk[top].h * (stk[top].num + tmp);//先计算一下之前的最大面积 
    20                 if (tot > ans) ans = tot;//更新答案 
    21                 tmp += stk[top].num;
    22                 top--;
    23             }
    24             stk[++top].h = height;
    25             stk[top].num = 1 + tmp;//更新宽度 
    26         }
    27         tmp = 0;
    28         while (top > 0) {//到最后的时候再做一遍,相当于加进了一个高度为0的矩形 
    29             tot = stk[top].h * (stk[top].num + tmp);
    30             if (tot > ans) ans = tot;
    31             tmp += stk[top].num;
    32             top--;
    33         }
    34         printf("%lld
    ", ans);
    35     }
    36     return 0;
    37 }
    View Code
  • 相关阅读:
    C#小型资源管理器
    C#换肤LrisSkin
    面向对象的24种设计模式
    七大设计原则
    非泛型集合和泛型集合
    C#经理评价系统
    深入C#.NET框架
    C#窗口航空总结
    java基础数据结构和语法
    HTML
  • 原文地址:https://www.cnblogs.com/Sundial/p/11837970.html
Copyright © 2011-2022 走看看