stack(数组模拟) POJ 2559 Largest Rectangle in a Histogram

 

题目传送门

 1 /*  2  题意:宽度为1,高度不等,求最大矩形面积  3  stack(数组模拟):对于每个a[i]有L[i],R[i]坐标位置 表示a[L[i]] < a[i] < a[R[i]] 的极限情况  4  st[]里是严格单调递增,若不记录的话还要O(n)的去查找L,R,用栈的话降低复杂度  5 */  6 #include <cstdio>  7 #include <cstring>  8 #include <algorithm>  9 #include <stack> 10 #include <iostream> 11 using namespace std; 12 13 typedef long long ll; 14 15 const int MAXN = 1e5 + 10; 16 const int INF = 0x3f3f3f3f; 17 int a[MAXN], L[MAXN], R[MAXN]; 18 int st[MAXN]; 19 20 int main(void) //POJ 2559 Largest Rectangle in a Histogram 21 { 22 // freopen ("POJ_2559.in", "r", stdin); 23 24 int n; 25 while (scanf ("%d", &n) == 1) 26  { 27 if (n == 0) break; 28 for (int i=1; i<=n; ++i) scanf ("%d", &a[i]); 29 memset (st, 0, sizeof (st)); 30 31 int p = 0; 32 for (int i=1; i<=n; ++i) 33  { 34 while (p >= 1 && a[st[p-1]] >= a[i]) p--; 35 L[i] = (p == 0) ? 0 : st[p-1]; 36 st[p++] = i; 37  } 38 39 p = 0; 40 for (int i=n; i>=1; --i) 41  { 42 while (p >= 1 && a[st[p-1]] >= a[i]) p--; 43 R[i] = (p == 0) ? n + 1 : st[p-1]; 44 st[p++] = i; 45  } 46 47 ll ans = 0; 48 for (int i=1; i<=n; ++i) 49  { 50 ans = max (ans, (ll) a[i] * (R[i] - L[i] - 1)); 51  } 52 printf ("%I64d\n", ans); 53  } 54 55 return 0; 56 }

 

你可能感兴趣的:(stack)