来源:互联网 发布:梦幻手游忽视法防数据 编辑:程序博客网 时间:2024/05/16 08:32

对栈有了一定得了解后,做了这道题:

 在横轴上放了n个相邻的矩形,每个矩形的宽度是1,而第i(1 ≤ i ≤ n)个矩形的高度是hi

这n个矩形构成了一个直方图。例如,下图中六个矩形的高度就分别是3, 1, 6, 5, 2, 3。



请找出能放在给定直方图里面积最大的矩形,它的边要与坐标轴平行。

对于上面给出的例子,最大矩形如下图所示的阴影部分,面积是10。

基本思路就是第一次输入矩形的高以后,并将其记录在一个结构体,同时在结构体记录矩形的宽,虽然是1,

但也需要记录,后面要用到,将此结构体变量入栈。然后每输入一个高并记录在结构体变量temp中,判断他

是否大于栈顶的高,若大于等于就入栈,否则,也就是小于栈顶的高,就计算栈顶的面积,并将栈顶的宽累

加到一个变量暂记为total_w,然后让其出栈,再次与栈顶比较,直到temp中的高大于等于栈顶元素的高后停

止,关键来了,将累加的total_w的值赋给temp的宽,目的可以在代码中体现出来。然后经过上面的重复输入,

判断,最后栈里剩下的肯定是递增排列的元素,挨个判断即可。通过代码,可能会理解的更深刻。。

[cpp] view plain copy
  1. #include <iostream>  
  2. #include <algorithm>  
  3. #include <cstring>  
  4. #include <cstdio>  
  5. #include <cmath>  
  6. #include <stack>  
  7.   
  8. using namespace std;  
  9.   
  10. struct node  
  11. {  
  12.     int h;  
  13.     int w;  
  14. };  
  15. int main()  
  16. {  
  17.     int n, totalw, maxn=0, cura;  
  18.     node temp;  
  19.     stack < node > s;  
  20.     cin >> n;  
  21.     for(int i=1; i<=n; ++i)  
  22.     {  
  23.         cin >> temp.h;  
  24.         temp.w=1;  
  25.         if(s.empty())  
  26.             s.push(temp);  
  27.         else  
  28.         {  
  29.             cura=totalw=0;  
  30.             if(temp.h>=s.top().h)  
  31.                 s.push(temp);  
  32.             else  
  33.             {  
  34.                 while(!s.empty())  
  35.                 {  
  36.                     if(temp.h<s.top().h)  
  37.                     {  
  38.                         totalw+=s.top().w;  
  39.                         cura=totalw*s.top().h;  
  40.                         if(cura>maxn)  
  41.                             maxn=cura;  
  42.                         s.pop();  
  43.                     }  
  44.                     else  
  45.                     {  
  46.                         break;  
  47.                     }  
  48.                 }  
  49.                 temp.w+=totalw;  
  50.                 s.push(temp);  
  51.             }  
  52.         }  
  53.     }  
  54.     totalw=cura=0;  
  55.     while(!s.empty())  
  56.     {  
  57.         totalw+=s.top().w;  
  58.         cura=s.top().h*totalw;  
  59.         if(cura>maxn)  
  60.             maxn=cura;  
  61.         s.pop();  
  62.     }  
  63.     cout << maxn << endl;  
  64.   
  65.   
  66.     return 0;  
  67. }  
0 0