poj2559 Largest Rectangle in a Histogram
洛谷上做过一道一样的题(P1719 最大加权矩形),但是没写博客...
现在已一个新高度来看待这题,沿用以前的方法,感觉很好(草稿纸模拟数小时后20分钟AC)
就是对于每一个位置,记录能够往右延伸多远。
然后反着做一遍,记录能向左多远。
单调栈算法。
当然也有扫一遍即可的算法,但是写着烦,就没写。
1 #include <cstdio> 2 using namespace std; 3 const int N = 100010; 4 typedef long long LL; 5 6 LL Q[N], t, h[N], l[N]; 7 8 inline void max(LL &a, const LL b) { 9 if(a < b) a = b; 10 return; 11 } 12 13 int main() { 14 int n; 15 while(scanf("%d", &n)) { 16 if(n == 0) { 17 break; 18 } 19 t = 0; 20 for(int i = 1; i <= n; i++) { 21 scanf("%lld", &h[i]); 22 } 23 h[n + 1] = 0; 24 for(int i = 1; i <= n + 1; i++) { 25 Q[++t] = i; 26 while(h[Q[t - 1]] > h[i]) { 27 l[Q[t - 1]] = i - Q[t - 1] - 1; 28 Q[t - 1] = Q[t--]; 29 } 30 } 31 t = 0; 32 for(int i = n; i >= 0; i--) { 33 Q[++t] = i; 34 while(h[Q[t - 1]] > h[i]) { 35 l[Q[t - 1]] += (Q[t - 1] - i); 36 Q[t - 1] = Q[t--]; 37 } 38 } 39 long long ans = 0; 40 for(int i = 1; i <= n; i++) { 41 max(ans, h[i] * l[i]); 42 } 43 printf("%lld\n", ans); 44 } 45 return 0; 46 }

浙公网安备 33010602011771号