HISTOGRA - 最大矩形面積(單調棧)

ruoye123456發表於2024-09-13

include<bits/stdc++.h>

using namespace std;

define x first

define y second

typedef pair<int,int> PII;
typedef long long ll;
typedef unsigned long long ull;
typedef unsigned int uint;
typedef vector VS;
typedef vector VI;
typedef vector<vector> VVI;
vector vx;
inline int mp(int x) {return upper_bound(vx.begin(),vx.end(),x)-vx.begin();}
inline int log_2(int x) {return 31-__builtin_clz(x);}
inline int popcount(int x) {return __builtin_popcount(x);}
inline int lowbit(int x) {return x&-x;}
const int N = 1e5+10;
int stk[N],a[N],w[N];
void solve()
{
//對於一個單調遞增序列最大矩形面積應該是列舉左端點乘以長度
int n;
while(cin>>n,n)
{
int tt = 0;
ll maxn = 0;
for(int i=1;i<=n;++i) cin>>a[i];
a[n+1] = 0;
stk[0] = 0;
//需要用width來維護累計矩形寬度
//i列舉到n+1為了彈出最後一個矩形注意要把a[n+1]賦值
for(int i=1;i<=n+1;++i)
{
if(a[i]>stk[tt]) stk[++tt] = a[i], w[tt] = 1;
else
{
int width = 0;
while(tt&&a[i]<stk[tt])
width += w[tt], maxn = max(maxn,(ll)width*stk[tt--]);
stk[++tt] = a[i], w[tt] = width + 1;
}
}
cout<<maxn<<'\n';
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int T = 1;
//cin>>T;
while(T--)
{
solve();
}
}

相關文章