ccf:2013-12-03最大的矩形(应试技巧 +解题思路 + 满分代码)

应试技巧

  • 根据数据范围反推时间复杂度,比如,数据范围n <= 1000,我们可以将时间复杂度控制在O(n²), O(n²)logn
  • 在时间复杂度允许的情况下,要写最容易AC的代码

题目

image-20211104173713257

解题思路

这个矩形的高度一定是某一个数字,所以枚举每一个数字0(n)对应矩形的面积,寻找最大值

确定了矩形的的高度,再确定矩形的长度,从当前枚举的这个数向两边寻找与比它小的那个数之间的距离(最坏的情况,找了整个序列长0(n))

所以0(n²)可以解出题目

代码实现

#include <iostream>
#include <algorithm>
#include <cstring>

using namespace std;

const int N = 1010;

int a[N];

int main()
{
    int n;
    cin >> n;

    for (int i = 1; i <= n; i ++)
    {
        cin >> a[i];
    }

    int res = 0; //记录答案

    for (int i = 1; i <= n; i ++) //枚举所有的高度
    {
        int l = i, r = i; //初始化左边界与右边界为当前枚举的值
        while (l >= 1 && a[l] >= a[i]) l --; //将边界移动到第一个小于该枚举值的地方
        while (r <= n && a[r] >= a[i]) r ++;
        res = max(res, a[i] * (r - l - 1)); //r - l - 1为矩形的长度
    }

    cout << res;

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_51800570/article/details/121148154
今日推荐