csp 最大的矩形

问题描述

  在横轴上放了n个相邻的矩形,每个矩形的宽度是1,而第i(1 ≤ i ≤ n)个矩形的高度是hi。这n个矩形构成了一个直方图。例如,下图中六个矩形的高度就分别是3, 1, 6, 5, 2, 3。



  请找出能放在给定直方图里面积最大的矩形,它的边要与坐标轴平行。对于上面给出的例子,最大矩形如下图所示的阴影部分,面积是10。

输入格式

  第一行包含一个整数n,即矩形的数量(1 ≤ n ≤ 1000)。
  第二行包含n 个整数h1, h2, … , hn,相邻的数之间由空格分隔。(1 ≤ hi ≤ 10000)。hi是第i个矩形的高度。

输出格式

  输出一行,包含一个整数,即给定直方图内的最大矩形的面积。

样例输入

6
3 1 6 5 2 3

样例输出

10

#include <iostream>
#include <cstdio>
#include <set>

using namespace std;
const int MAX = 50005;
struct node{
    int x,y,s;

    friend bool operator <(const node& n1,const node& n2){
        if(n1.y == n2.y)return n1.x < n2.x;//when y1 = y2 then compare x1 and x2
        else return n1.y < n2.y;//when y1 not equl y2 then compare y1 and y2
    }
};

int main(int argc, char const *argv[]) {
    int n,h;

    scanf("%d%d",&n,&h);
    int q[MAX] = {0};

    set<node> st;//sort with y
    for(int i = 0;i < h;i++){
        node nd;
        scanf("%d%d%d",&nd.x,&nd.y,&nd.s);

        st.insert(nd);
    }
    //record the number of trees
    int sum = 0;
    for(auto k:st){
        int tem1 = 0,tem2 = 0;
        for(int i = k.x;i <= k.y;i++)
            if(q[i] == 1)tem1++;//these points can be borrow

        tem2 = k.s - tem1;//The number of points that need to be increased

        for(int i = k.y;i > 0;i--){
            if(tem2 <= 0)break;//key issue  -> '<='
            if(q[i] != 1){
                q[i] = 1;
                sum++;//add the number of tree
                tem2--;
            }
        }
    }

    printf("%d\n",sum);
    return 0;
}
发布了85 篇原创文章 · 获赞 40 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/WX_1218639030/article/details/84844653
CSP