单调栈做法
Blog
Sol.1 枚举直线
注意到最大矩形的四边都在障碍所在直线上,所以考虑枚举端点以及其直线即可。具体地,将障碍点按横坐标排序之后,枚举矩形的左边界,然后按顺序枚举右边界,将前面包含了的点更新当前矩形的上下边界,取最大值即可。注意要将牛场的四个角加入障碍中才能保证正确性。
时间复杂度
Sol.2 单调栈
注意到非障碍所在横纵坐标是无用的,考虑离散化。那么问题就转化为
但此题有一点特殊,我们之前的做法搬到这道题上来时,一个矩形只能被它中间的坐标枚举到。也就是说,如果最大矩形的两个横坐标在离散化数组中是相邻的,就没有能枚举到这个矩形的点了。于是考虑枚举每一个离散化数组中相邻的横坐标,此时最大纵坐标就是牛场的宽,取最大值即可。
该做法依然要把牛场边界加入离散化,并且空间限制较紧,需要用到滚动数组技巧。
时间复杂度
#include <bits/stdc++.h>
#define fi first
#define se second
using namespace std;
typedef long long ll;
using pi=pair<int,int>;
const int N=5005;
int n,nx,ny,lshx[N],lshy[N],cntx,cnty,pre[N],x[N],y[N],dp[N][N],lx[N],rx[N],stk[N],tp,ans;
bitset<N>blk[N];
int getrkx(int x)
{
return (lower_bound(lshx+1,lshx+cntx+1,x)-lshx);
}
int getrky(int x)
{
return (lower_bound(lshy+1,lshy+cnty+1,x)-lshy);
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>nx>>ny>>n;
for(int i=1;i<=n;i++)
{
cin>>x[i]>>y[i];
lshx[++cntx]=x[i];
lshy[++cnty]=y[i];
}
lshx[++cntx]=0;
lshy[++cnty]=0;
lshx[++cntx]=nx;
lshy[++cnty]=ny;
sort(lshx+1,lshx+cntx+1);
cntx=unique(lshx+1,lshx+cntx+1)-lshx-1;
sort(lshy+1,lshy+cnty+1);
cnty=unique(lshy+1,lshy+cnty+1)-lshy-1;
for(int i=1;i<=n;i++)blk[getrkx(x[i])][getrky(y[i])]=1;
for(int i=1;i<=cntx;i++)
{
for(int j=1;j<=cnty;j++)
{
dp[i][j]=lshx[i]-pre[j];
if(blk[i][j])pre[j]=lshx[i];
}
}
for(int i=1;i<=cntx;i++)
{
memset(lx,0,sizeof(lx));
memset(rx,0,sizeof(rx));
tp=0;
for(int j=1;j<=cnty;j++)
{
while(tp&&dp[i][stk[tp]]>=dp[i][j])tp--;
if(tp==0)lx[j]=0;
else lx[j]=lshy[stk[tp]];
stk[++tp]=j;
}
tp=0;
for(int j=cnty;j>=1;j--)
{
while(tp&&dp[i][stk[tp]]>=dp[i][j])tp--;
if(tp==0)rx[j]=ny;
else rx[j]=lshy[stk[tp]];
stk[++tp]=j;
}
for(int j=1;j<=cnty;j++)
{
ans=max(ans,dp[i][j]*(rx[j]-lx[j]));
if(j>1)
ans=max(ans,lshx[i]*(lshy[j]-lshy[j-1]));
}
}
cout<<ans;
return 0;
}