Hdu 1506 Largest Rectangle in a Histogram (DP求最大长方形面积)
2014-03-11 16:36
567 查看
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1506
思路:用dp思想求得每一列能往左,右延伸的最长长度。不能一个一个遍历,学会处理后一个数据时用上 上一个已更新的数据
注意:用__int64 %I64 输入输出(可能TLE)
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define LL __int64
#define maxn 100000+5
LL h[maxn];
int l[maxn],r[maxn];
int main(){
int n;
while(scanf("%d",&n)!=EOF && n){
h[0] = h[n+1] = -1;
for (int i = 1; i <= n; i++){
scanf("%I64d",&h[i]);
l[i] = r[i] = i;
}
for (int i = 1; i <= n; i++){
while( l[i] >= 1 && h[ l[i]-1 ] >= h[i]){
l[i] = l[ l[i]-1 ];
}
}
for (int i = n; i >= 1; i--)
{
while( r[i] <= n && h[ r[i]+1 ] >= h[i]){
r[i] = r[ r[i]+1 ];
}
}
LL ans = 0,tmp = 0;
for (int i = 1; i <= n; i++)
{
tmp = (r[i]-l[i]+1)*h[i];
//ans = max(ans,tmp);
if(ans < tmp)ans = tmp;
}
printf("%I64d\n",ans);
}
return 0;
}
思路:用dp思想求得每一列能往左,右延伸的最长长度。不能一个一个遍历,学会处理后一个数据时用上 上一个已更新的数据
注意:用__int64 %I64 输入输出(可能TLE)
代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define LL __int64
#define maxn 100000+5
LL h[maxn];
int l[maxn],r[maxn];
int main(){
int n;
while(scanf("%d",&n)!=EOF && n){
h[0] = h[n+1] = -1;
for (int i = 1; i <= n; i++){
scanf("%I64d",&h[i]);
l[i] = r[i] = i;
}
for (int i = 1; i <= n; i++){
while( l[i] >= 1 && h[ l[i]-1 ] >= h[i]){
l[i] = l[ l[i]-1 ];
}
}
for (int i = n; i >= 1; i--)
{
while( r[i] <= n && h[ r[i]+1 ] >= h[i]){
r[i] = r[ r[i]+1 ];
}
}
LL ans = 0,tmp = 0;
for (int i = 1; i <= n; i++)
{
tmp = (r[i]-l[i]+1)*h[i];
//ans = max(ans,tmp);
if(ans < tmp)ans = tmp;
}
printf("%I64d\n",ans);
}
return 0;
}
相关文章推荐
- 基于Android中dp和px之间进行转换的实现代码
- Android中dip、dp、sp、pt和px的区别详解
- Android根据分辨率进行单位转换-(dp,sp转像素px)
- android 尺寸 dp,sp,px,dip,pt详解
- Android 不同分辨率下如何使字体大小随之变化
- HDU4758 AC自动机+DP (HDU4758与HDU2222)
- [LeetCode] Distinct Subsequences
- [LeetCode] Interleaving String
- [LeetCode] Unique Binary Search Tree
- [LeetCode] Edit Distance
- [LeetCode] Minimum Path Sum
- [LeetCode] Unique Paths
- [LeetCode] Unique Paths II
- [LeetCode] Maximum Subarray
- [LeetCode] Trapping Rain Water
- [LeetCode] Binary Tree Maximum Path Sum
- [LeetCode] Best Time to Buy and Sell Stock III
- [LeetCode] Scramble String
- [LeetCode] Longest Palindromic Substring
- 状态压缩DP codeforces 244 Problem C. The Brand New Function 和 codeforces 165 E. Compatible Numbers