zoukankan      html  css  js  c++  java
  • poj 2559 Largest Rectangle in a Histogram 栈

    // 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 ' ' #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 ",res); } int main() { //freopen("G:\Code\1.txt","r",stdin); while(scanf("%d",&n)!=EOF&&n){ init(); } return 0; }


  • 相关阅读:
    JS站点
    1011 World Cup Betting (20分)
    1007 Maximum Subsequence Sum (25分)(动态规划DP)
    1006 Sign In and Sign Out (25分)
    1005 Spell It Right (20分)
    1004 Counting Leaves (30分)(DFS)
    1003 Emergency (25分)(Dijkstra算法)
    1002 A+B for Polynomials (25分)
    1001 A+B Format (20分)
    canvas
  • 原文地址:https://www.cnblogs.com/jzssuanfa/p/6814535.html
Copyright © 2011-2022 走看看