1. 程式人生 > >poj 2559 Largest Rectangle in a Histogram 棧

poj 2559 Largest Rectangle in a Histogram 棧

hist func opc txt class sse typedef ++ limit

// poj 2559 Largest Rectangle in a Histogram 棧
// 
// n個矩形排在一塊,不同的高度,讓你求最大的矩形的面積(矩形緊挨在一起)
//
// 這道題用的是數據結構做。也能夠遞推做。眼下僅僅會數據結構的
//
// 對於每一個高度h,求一個左邊界L和右邊界R,分別表示的意義是
// L是下標為j的矩形的高度的hj小於當前h的最大的j的值。

則依據定義 // 我們能夠知道j到i之間的h都是大於當前的hi的。 // R是下標為k的矩形的高度的hk大於當前h的最小的k的值。則依據定義 // 我們能夠知道i到k之間的h都是大於當前的hi的。 // 則最後的結果就是max( ( R[i] - L[i] ) * h[i]). // // 詳細實現是用一個棧依次保存每一個矩形的高度。 // 設棧中的元素從上到下的值是x[i](x[i] > x[i+1] && h[x[i]] > h[x[i+1]]) // // 在計算L[i]的時候。當棧頂元素j滿足h[j]>=h[i]時。一直出棧。直到j=0或者 // h[j] < h[i] 的時候,我們就求出了最大的h[j]>=h[i]的j的最小值即j+1 // // 在計算R[i]的時候,當棧頂元素j滿足h[j]>=h[i]時,一直出棧。知道j=0或者 // h[j] < h[i] 的時候。我們就求除了最小的h[j]>=h[i]的j的最大值即j。 // // 所要註意的是 // // 計算L的時候要從左邊開始掃描,此時棧中須要的是1,2,...i的值 // 計算R的時候要從右邊開始掃描,此時棧中須要的是i+1...n的值 // // // 感悟: // // 從這道題中就能夠發現數據結構棧的魅力的所在,個人感覺數據結構非常奇妙, // 也更加篤定了我要學數據結構的決心。

// // 繼續練 #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <cfloat> #include <climits> #include <cmath> #include <complex> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <deque> #include <functional> #include <iostream> #include <list> #include <map> #include <numeric> #include <queue> #include <set> #include <stack> #include <vector> #define ceil(a,b) (((a)+(b)-1)/(b)) #define endl ‘\n‘ #define gcd __gcd #define highBit(x) (1ULL<<(63-__builtin_clzll(x))) #define popCount __builtin_popcountll typedef long long ll; using namespace std; const int MOD = 1000000007; const long double PI = acos(-1.L); const int maxn = 1e5 + 8; int a[maxn]; int st[maxn]; int n; int L[maxn]; int R[maxn]; void init(){ for (int i=0;i<n;i++) scanf("%d",&a[i]); int t = 0; for (int i=0;i<n;i++){ while(t>0 && a[st[t-1]]>=a[i]) t--; L[i] = t==0 ? 0 : st[t-1] + 1; st[t++] = i; } t = 0; for (int i=n-1;i>=0;i--){ while(t>0 && a[st[t-1]] >= a[i]) t--; R[i] = t==0 ? n : st[t-1]; st[t++] = i; } long long res = 0; for (int i=0;i<n;i++){ res = max(res,( R[i] - L[i] ) * (long long)a[i]); } printf("%lld\n",res); } int main() { //freopen("G:\\Code\\1.txt","r",stdin); while(scanf("%d",&n)!=EOF&&n){ init(); } return 0; }


poj 2559 Largest Rectangle in a Histogram 棧