luogu SP1805 HISTOGRA - Largest Rectangle in a Histogram

Dear 丶 2021-11-02 15:44 182阅读 0赞

传送门

今天是2019.6.4 距离NOIP2019还有157天

这是一道单调栈的好题

记得高一下暑假集训的时候肖宇朔学长讲过

今天突然想到了这道题拿出来再做一遍

应该是2019年第一道正常难度的题

题解原先在**洛谷上发过一遍了**

这里再发一遍

题解:只需从左到右维护一个高度递增的栈并且记录每个元素的宽度

每弹出一个元素的时候用它更新答案

为什么呢

因为所有可能成为答案的矩形它的四条边都无法再向四周扩散

每一个给定的矩形宽度都为一,所以我们不妨从左到右遍历一遍整个矩形图

假设第一个矩形高是5,那么包含它的可能成为答案的矩形的高度一定是5(显然)

那么第一个矩形的右面有多少个连续不断的高于第一个矩形矩形就决定了包含它的可能答案(tot)

如果遇到小于5的一个矩形,就弹出栈中元素,由此合并出可能的答案

最后枚举答案求出最大值即可

上代码

  1. #include<cstdio>
  2. #include<cstring>
  3. #include<cmath>
  4. #include<cctype>
  5. #include<cstdlib>
  6. #include<string>
  7. #include<iostream>
  8. #include<algorithm>
  9. #include<set>
  10. #include<map>
  11. #include<queue>
  12. #include<stack>
  13. #include<vector>
  14. #define enter puts("")
  15. #define space putchar(' ')
  16. using namespace std;
  17. typedef long long ll;
  18. ll read()
  19. {
  20. ll op = 1, ans = 0;
  21. char ch = getchar();
  22. while(ch < '0' || ch > '9')
  23. {
  24. if(ch == '-') op = 0;
  25. ch = getchar();
  26. }
  27. while(ch >= '0' && ch <= '9')
  28. {
  29. ans *= 10;
  30. ans += ch - '0';
  31. ch = getchar();
  32. }
  33. return op ? ans : -ans;
  34. }
  35. void write(ll x)
  36. {
  37. if(x < 0)
  38. {
  39. x = -x;
  40. putchar('-');
  41. }
  42. if(x >= 10) write(x / 10);
  43. putchar(x % 10 + '0');
  44. }
  45. const int N = 100005;
  46. struct Drug
  47. {
  48. int height;
  49. int count;
  50. };
  51. Drug st[N];
  52. ll top, h, n, ans, tot, tmp;//tmp存宽度,tot存可能的矩形面积
  53. int main()
  54. {
  55. while(scanf("%d", &n) != EOF && n)
  56. {
  57. top = 0;
  58. ans = 0;
  59. for(int i = 1; i <= n; i++)
  60. {
  61. h = read();
  62. tmp = 0;
  63. while(top > 0 && st[top - 1].height >= h)//维护单调栈
  64. {
  65. tot = st[top - 1].height * (st[top - 1].count + tmp);
  66. if (tot > ans) ans = tot;
  67. tmp += st[top - 1].count;
  68. --top;
  69. }
  70. st[top].height = h;
  71. st[top].count = 1 + tmp;
  72. ++top;
  73. }
  74. tmp = 0;
  75. while(top > 0)//出栈
  76. {
  77. tot = st[top - 1].height * (st[top - 1].count + tmp);
  78. ans = max(tot, ans);
  79. tmp += st[top - 1].count;
  80. --top;
  81. }
  82. write(ans);
  83. enter;
  84. }
  85. return 0;
  86. }

转载于:https://www.cnblogs.com/thx666/p/10976620.html

发表评论

表情:
评论列表 (有 0 条评论,182人围观)

还没有评论,来说两句吧...

相关阅读