HDU 1506 Largest Rectangle in a Histogram(DP)
Largest Rectangle in a Histogram
Largest Rectangle in a Histogram
大意:找到面积最大的矩形
思路:对于每一个a[i],用dp找出a[i]左边和右边连续大于自己的数的长度
l[i]表示比a[i]大的数连续的最左边的位置
r[i]表示比a[i]大的数连续的最右边的位置
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <map> 2 #include <stack> 3 #include <queue> 4 #include <math.h> 5 #include <stdio.h> 6 #include <string.h> 7 #include <iostream> 8 #include <algorithm> 9 #define LL __int64 10 using namespace std; 11 12 LL a[100010], dp_l[100010], dp_r[100010]; 13 14 void run() 15 { 16 int n; 17 while(~scanf("%d", &n) && n) 18 { 19 for(int i = 1; i <= n; i++) 20 { 21 scanf("%I64d", &a[i]); 22 } 23 dp_l[1] = 1; 24 dp_r[n] = n; 25 for(int i = 2; i <= n; i++) 26 { 27 int t = i; 28 while(t > 1 && a[i] <= a[t-1]) ///DP 29 { 30 t = dp_l[t-1]; 31 } 32 dp_l[i] = t; 33 } 34 for(int i = n-1; i >= 1; i--) 35 { 36 int t = i; 37 while(t < n && a[i] <= a[t+1]) ///Dp 38 { 39 t = dp_r[t+1]; 40 } 41 dp_r[i] = t; 42 } 43 LL max = 0; 44 for(int i = 1; i <= n; i++) 45 { 46 if((dp_r[i]-dp_l[i]+1)*a[i] > max) 47 max = (dp_r[i]-dp_l[i]+1)*a[i]; 48 } 49 printf("%I64d\n", max); 50 } 51 } 52 53 int main(void) 54 { 55 run(); 56 57 return 0; 58 }