Description
Input
Output
Sample Input
1 0 1
0 1 0
1 0 0
Sample Output
6
HINT
N, M ≤ 2000
題解
此題有兩種解法1.單調棧2.懸線法
單調棧:
由於棋盤是相間式的,所以可以把橫縱座標爲奇數的全部異或(偶數也行),這樣問題就轉化成了找全0或1的矩陣,可以用單調棧解決,先預處理每一行連續1的個數,然後枚舉縱行,對橫行進行單調棧,維護一個單調遞增的棧,出現一個比棧頂元素小的數就計算面積跟新答案,注意棧中橫行的標號是連續的,新進來的i減去s[top].num就是中間矩形的高。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=100010;
int top=0,ans1,ans2,n,m,h[2010][2010],a[2010][2010];
struct node{
int num,h;
}s[maxn];
inline void push(int i,int h){
int now=i;
while(top&&s[top].h>h){
ans1=max(ans1,min(i-s[top].num,s[top].h)*min(i-s[top].num,s[top].h));
ans2=max(ans2,s[top].h*(i-s[top].num));
now=s[top--].num;
}
s[++top]=(node){now,h};
}
void work(){
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
h[i][j]=a[i][j]?h[i][j-1]+1:0;
for(int j=1;j<=m;j++)
{
top=0;
for(int i=1;i<=n;i++)
push(i,h[i][j]);
push(n+1,0);
}
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++){
scanf("%d",&a[i][j]);
if((i+j)%2==1)
a[i][j]^=1;
}
work();
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++){
a[i][j]^=1;
}
work();
printf("%d\n%d\n",ans1,ans2);
return 0;
}
懸線法:
所謂懸線法就是,每一列都假設有一條線記錄這條線的高度,能到達的左端點,能到達的右端點。具體的細節在代碼中標註。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=100010;
int up[maxn],topl[maxn],topr[maxn],ans1,ans2,nowl,nowr,n,m,a[2010][2010];
void work(){
memset(up,0,sizeof(up));
for(int i=1;i<=m;i++) topl[i]=1,topr[i]=m;
for(int i=1;i<=n;i++){
nowl=0;nowr=m+1;
for(int j=1;j<=m;j++){
if(a[i][j]){
up[j]=0;//記錄線的長度
nowl=j;//記錄當前障礙物的位置
topl[j]=1;//記錄線能走到的左端點
}
else{
up[j]++;
topl[j]=max(topl[j],nowl+1);
}
}
for(int j=m;j>=1;j--){
if(a[i][j]){
nowr=j;
topr[j]=m;//記錄線能走到的右端點
}
else{
topr[j]=min(topr[j],nowr-1);
ans1=max(ans1,min(topr[j]-topl[j]+1,up[j])*min(topr[j]-topl[j]+1,up[j]));
ans2=max(ans2,(topr[j]-topl[j]+1)*up[j]);
}
}
}
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++){
scanf("%d",&a[i][j]);
if((i+j)%2==1)
a[i][j]^=1;
}
work();
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++){
a[i][j]^=1;
}
work();
printf("%d\n%d\n",ans1,ans2);
return 0;
}