Two Buildings

Two Buildings

【分治】【决策单调性】
There are n buildings along a horizontal street. The buildings are next to each other along the street, and the i-th building from left to right has width 1 and height hi. Among the n buildings, we are to find two buildings, say the i-th building and j-th building with i<j, such that (hi+hj)∗(j−i) is maximized.

For example, the right figure shows 5 buildings, with heights 1, 3, 2, 5, 4, from left to right. If we choose the first 2 buildings, then we get (1+3)∗(2−1)=4. If we choose the first and fifth buildings, then we (1+4)∗(5−1)=20. The maximum value is achieved by the second and fifth buildings with heights 3 and 4, respectively: (3+4)∗(5−2)=21.

Write a program that, given a sequence of building heights, prints max1≤i<j≤n(hi+hj)∗(j−i).

Input
Your program is to read from standard input. The input starts with a line containing an integer n (2≤n≤1,000,000), where n is the number of buildings. The buildings are numbered 1 to n from left to right. The second line contains the heights of n buildings separated by a space such that the i-th number is the height hi of the i-th building (1≤hi≤1,000,000).

Output
Your program is to write to standard output. Print exactly one line. The line should contain max1≤i<j≤n(hi+hj)∗(j−i).

Examples

Input
5
1 3 2 5 4
Output
21

Input
5
8 3 6 3 1
Output
36

解析:对于任意i,j 若存在k>j并且h[k]>h[j]则j不可能是我们想要的右界,可以把他排除,同理也可以对左界进行排除,然后左界的数据和右界的数据进行配对找出最大值

对于(hi+hj)∗(j−i)等于(hi-(-hj))∗(j−i)可以表示成一个矩形的面积

而对于左右界的数据来说:先去中间值mid再右侧找到使结果最大的pos点,对于mid左侧的数据来说(右侧同理)
在这里插入图片描述
图片转自https://www.cnblogs.com/wjyyy/p/CF102920L.html

所以只需要找到mid和pos配对 以及mid左侧的点和pos及左侧进行配对,以及mid右侧的点和pos及右侧的点进行配对

AC代码:

#include<iostream>
using namespace std;
int a[1000010];
int zz[1000010][2];
int yy[1000010][2];
int conz=0,cony=0;
long long ans=0;
long long jc(int x,int y)
{
    return 1LL*(zz[x][0]+yy[y][0])*(yy[y][1]-zz[x][1]);
}
void fact(int l1,int r1,int l2,int r2)
{
    int mid=l1+r1>>1;
    int pos=l2;
    for(int i=l2;i<=r2;i++)
        if(jc(mid,i)>jc(mid,pos))
        pos=i;
    ans=max(ans,jc(mid,pos));
    if(mid-1>=l1) fact(l1,mid-1,pos,r2);
    if(mid+1<=r1) fact(mid+1,r1,l2,pos);
}
int main()
{
    int n;
    cin>>n;
    for(int i=1;i<=n;i++) scanf("%d",a+i);
    int pos1=0,pos2=0;
    for(int i=1;i<=n;i++)
    {
        if(a[i]>pos1) pos1=a[i],zz[++conz][0]=a[i],zz[conz][1]=i;
        if(a[n-i+1]>pos2) pos2=a[n-i+1],yy[++cony][0]=a[n-i+1],yy[cony][1]=n-i+1;
    }
    fact(1,conz,1,cony);
    cout<<ans<<endl;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值