标签:print show acm ret ges i++ ram name amp
连接:http://acm.hdu.edu.cn/showproblem.php?pid=1506
题意:给一个柱状图,每个小矩形宽为1,求这个柱状图最大子矩形的面积
思路:用单调栈求出每个小矩形所能组成最大矩形的左宽和有宽,分别存在l[i] , r[i]数组里,然后 ans = max( h[i] * ( r[i] - l[i] )
注意:int * int 结果可能超过2^32
代码:
#include <iostream> #include <algorithm> #define ll long long #define maxn 100000+100 //#define scanf scanf_s using namespace std; int n; int h[maxn]; int l[maxn], r[maxn]; int st[maxn]; void solve() { int t = 0; for (int i = 0; i < n; i++) { while (t > 0 && h[st[t - 1]] >= h[i]) t--; l[i] = t == 0 ? 0 : (st[t - 1] + 1); st[t++] = i; } t = 0; for (int i = n-1; i >= 0; i--) { while (t > 0 && h[st[t - 1]] >= h[i]) t--; r[i] = t == 0 ? n : st[t - 1]; st[t++] = i; } ll res = 0; for (int i = 0; i < n; i++) { res = max(res, 1ll*h[i] * (r[i] - l[i])); } printf("%lld\n", res); } int main() { while (scanf("%d", &n) && n) { for (int i = 0; i < n; i++) { scanf("%d", &h[i]); } solve(); } return 0; }
HDU-Largest Rectangle in a Histogram-1506 单调栈
标签:print show acm ret ges i++ ram name amp
原文地址:https://www.cnblogs.com/the-way-of-cas/p/9594573.html