首页 > 代码库 > [dp]POJ2559 && HDOJ1506 Largest Rectangle in a Histogram

[dp]POJ2559 && HDOJ1506 Largest Rectangle in a Histogram

题意 给n个条形的高度, 问能放的最大矩形面积

分析: 从左到右 从右到左 各搞一遍

分别记录      L[i]记录列(从前往后)标 第几列开始 可以往后放高度为a[i]的矩形

       R[i]记录列(从后往前)标 第几列开始 可以往前放高度为a[i]的矩形

 R[i]-L[i]+1即为高度为a[i]的矩形能横穿的列数

再乘个a[i]即为面积  遍历所有高度 求最大值即可

 

ps.注意范围 面积要用LL

pps.注意 max((int), (LL)) 的CE

 

 1 #include <cstdio> 2 #include <cstdlib> 3 #include <cstring> 4 #include <climits> 5 #include <cctype> 6 #include <cmath> 7 #include <string> 8 #include <sstream> 9 #include <iostream>10 #include <algorithm>11 #include <iomanip>12 using namespace std;13 #include <queue>14 #include <stack>15 #include <vector>16 #include <deque>17 #include <set>18 #include <map>19 typedef long long LL;20 typedef long double LD;21 #define pi acos(-1.0)22 #define lson l, m, rt<<123 #define rson m+1, r, rt<<1|124 typedef pair<int, int> PI;25 typedef pair<int, PI> PP;26 #ifdef _WIN3227 #define LLD "%I64d"28 #else29 #define LLD "%lld"30 #endif31 //#pragma comment(linker, "/STACK:1024000000,1024000000")32 //LL quick(LL a, LL b){LL ans=1;while(b){if(b & 1)ans*=a;a=a*a;b>>=1;}return ans;}33 //inline int read(){char ch=‘ ‘;int ans=0;while(ch<‘0‘ || ch>‘9‘)ch=getchar();while(ch<=‘9‘ && ch>=‘0‘){ans=ans*10+ch-‘0‘;ch=getchar();}return ans;}34 inline void print(LL x){printf(LLD, x);puts("");}35 //inline void read(double &x){char c = getchar();while(c < ‘0‘) c = getchar();x = c - ‘0‘; c = getchar();while(c >= ‘0‘){x = x * 10 + (c - ‘0‘); c = getchar();}}36 37 #define N 10000538 int a[N], L[N], R[N];39 int main()40 {41 #ifndef ONLINE_JUDGE42     freopen("in.txt", "r", stdin);43     freopen("out.txt", "w", stdout);44 #endif45     int n;46     while(~scanf("%d", &n) && n)47     {48         for(int i=0;i<n;i++)49             scanf("%d", &a[i]);50         memset(L, 0, sizeof(L));51         memset(R, 0, sizeof(R));52         for(int i=0;i<n;i++)53         {54             L[i]=i;55             while(L[i]>0 && a[L[i]-1]>=a[i])56                 L[i]=L[L[i]-1];57         }58         for(int i=n-1;i>=0;i--)59         {60             R[i]=i;61             while(R[i]<n-1 && a[R[i]+1]>=a[i])62                 R[i]=R[R[i]+1];63         }64         LL ans=0;65         for(int i=0;i<n;i++)66             ans=max(ans, (LL)(R[i]-L[i]+1)*a[i]);67         print(ans);68     }69     return 0;70 }
HDOJ1506

 

[dp]POJ2559 && HDOJ1506 Largest Rectangle in a Histogram