zoukankan      html  css  js  c++  java
  • AcWing 131 直方图中最大的矩形 (单调栈)

    题目链接:https://www.acwing.com/problem/content/133/

    维护一个栈,使得栈内矩形高度单调递增,
    如果当前矩形比栈顶高度高,则之间入栈,
    否则不断取出栈顶,直到栈为空或栈顶高度比当前矩形小

    出栈过程中累计被弹出的矩形的宽度之和,没弹出一个矩形,就用其高度乘上累计宽度来更新答案,
    出栈过程结束后,把一个高度为当前高度,宽度为累计值的新矩形入栈,相当于将之前的矩形合并成一个新矩形

    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<iostream>
    #include<cmath>
    #include<stack>
    #include<queue>
    using namespace std;
    typedef long long ll;
    
    const int maxn = 100010;
    
    int n;
    int a[maxn], wid[maxn];
    
    int sta[maxn], tail = 0;
    
    ll read(){ ll s=0,f=1; char ch=getchar(); while(ch<'0' || ch>'9'){ if(ch=='-') f=-1; ch=getchar(); } while(ch>='0' && ch<='9'){ s=s*10+ch-'0'; ch=getchar(); } return s*f; }
    
    int main(){
    	while(1){
    		ll ans = 0; tail = 0;
    		memset(sta,0,sizeof(sta)); 
    		n = read();
    		if(!n) break;
    		for(int i=1;i<=n;++i) a[i] = read();
    		a[++n] = 0;
    		
    		for(int i=1;i<=n;++i){
    			ll width = 0;
    			while(a[i] < sta[tail] && tail > 0){
    				width += wid[tail];
    				ans = max(ans, 1ll * width * sta[tail--]);
    			}
    			sta[++tail] = a[i]; wid[tail] = width + 1;
    		}
    		
    		printf("%lld
    ",ans);
    	}
    
    	return 0;
    }
    
  • 相关阅读:
    两个51相互之间单片机如何进行串口通信
    (stm32f103学习总结)—stm32pwm
    (stm32f103学习总结)—stm32 PMW输出实验
    cpu指令如何读写硬盘
    线程进程同步
    stm32+lwip
    opc
    open62541-server编程
    linux 下time函数
    close与shutdown
  • 原文地址:https://www.cnblogs.com/tuchen/p/13937135.html
Copyright © 2011-2022 走看看