单调栈求 区间长度和区间最大值

本文介绍了一种使用单调栈在二维矩阵中寻找由数字1组成的第二大面积的方法。通过优化算法,实现了在O(n)的时间复杂度内找到每个元素左侧或右侧最近的小于当前元素的值。文中提供了一个完整的C++实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

求由1组成的第二大面积

    00111000  
    00111010
    00010010
    00000000
    
    00111000
    00222010
    00030020
    00000000
#pragma GCC optimize(1)
#pragma GCC optimize(2)
#pragma GCC optimize(3,"Ofast","inline")
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int sum[2050][2050];
int a[2050][2050];
int n,m;
///单调栈基本应用:
///可以在O(n)下求出一个序列中
///每个元素 向右 或 向左 比它 小 或 大 的第一个元素
struct node
{
    ll pos,val;
} s[100500];
bool cmp(ll a,ll b)
{
    return a>b;

}
int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1; i<=n; i++)
        for(int j=1; j<=m; j++)
            scanf("%1d",&a[i][j]);
    for(int i=1; i<=n; i++)
    {
        for(int j=1; j<=m; j++)
        {
            if(a[i][j])
                sum[i][j]=sum[i-1][j]+a[i][j];
            else sum[i][j]=0;
        }
    }
    ll ans=0;
    ll max1=0,max2=0;
    for(int i=1; i<=n; i++)
    {
        ll top=0;
        for(int j=1; j<=m+1; j++) ///当j=m+1时,清空栈
        {
            if(top==0)
            {
                s[++top]= {j,sum[i][j]};
            }
            else
            {
                while(s[top].val>sum[i][j])
                {
                    ll temp[10]= {0};
                    temp[1]=(ll)(j-s[top-1].pos-1)*(ll)s[top].val;
                    temp[2]=(ll)(j-s[top-1].pos-2)*(ll)s[top].val;
                    temp[3]=(ll)(j-s[top-1].pos-1)*(ll)(s[top].val-1);
                    temp[4]=max1;
                    temp[5]=max2;
                    sort(temp+1,temp+1+5,cmp);
                    max1=temp[1];
                    max2=temp[2];
                    top--;
                }
                s[++top]= {j,sum[i][j]};
            }
        }
    }
    printf("%lld\n",max2);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值