poj 2559 单调栈 ***

给出一系列的1*h的矩形,求矩形的最大面积。
如图:poj 2559 单调栈 ***

题解链接:点我

 

 1 #include <iostream>

 2 #include <cstdio>

 3 using namespace std;

 4 

 5 const int N = 100005;

 6 

 7 struct Elem

 8 {

 9     int height;

10     int count;

11 };

12 

13 Elem stack[N];

14 int top;

15 

16 int main()

17 {

18     int height, n;

19     long long ans, tot, tmp;

20     while (scanf("%d", &n) != EOF && n)

21     {

22         top = 0;

23         ans = 0;

24         for (int i = 0; i < n; ++i)

25         {

26             scanf("%d", &height);

27             tmp = 0;

28             while (top > 0 && stack[top - 1].height >= height)

29             {

30                 tot = stack[top - 1].height * (stack[top - 1].count + tmp);

31                 if (tot > ans) ans = tot;

32                 tmp += stack[top - 1].count;

33                 --top;

34             }

35             stack[top].height = height;

36             stack[top].count = 1 + tmp;

37             ++top;

38         }

39         tmp = 0;

40         while (top > 0)

41         {

42             tot = stack[top - 1].height * (stack[top - 1].count + tmp);

43             if (tot > ans) ans = tot;

44             tmp += stack[top - 1].count;

45             --top;

46         }

47         printf("%lld\n", ans);

48     }

49     return 0;

50 }

 

你可能感兴趣的:(poj)