Largest Submatrix
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 1488 Accepted Submission(s): 716
Problem Description
Now here is a matrix with letter 'a','b','c','w','x','y','z' and you can change 'w' to 'a' or 'b', change 'x' to 'b' or 'c', change 'y' to 'a' or 'c', and change 'z' to 'a', 'b' or 'c'. After you changed it, what's the largest submatrix with the same letters
you can make?
Input
The input contains multiple test cases. Each test case begins with m and n (1 ≤ m, n ≤ 1000) on line. Then come the elements of a matrix in row-major order on m lines each with n letters. The input ends once EOF is met.
Output
For each test case, output one line containing the number of elements of the largest submatrix of all same letters.
Sample Input
2 4 abcw wxyz
Sample Output
3
思路:其实就是算3次最大空白子矩阵问题,用n方算法,l[i][j]和r[i][j]表示在i行j点上方连续的空白列可以向左右扩展的最远距离。
AC代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
char s[1010][1010];
int v[1010][1010],ans,n,m,l[1010][1010],r[1010][1010];
void solve()
{ int i,j,k;
for(i=1;i<=n;i++)
{ v[i][0]=-1;
v[i][m+1]=-1;
for(j=1;j<=m;j++)
while(v[i][j]<=v[i][l[i][j]-1])
l[i][j]=l[i][l[i][j]-1];
for(j=m;j>=1;j--)
while(v[i][j]<=v[i][r[i][j]+1])
r[i][j]=r[i][r[i][j]+1];
for(j=1;j<=m;j++)
ans=max(ans,v[i][j]*(r[i][j]-l[i][j]+1));
}
}
int main()
{ int i,j,k;
while(~scanf("%d%d",&n,&m))
{ ans=0;
for(i=1;i<=n;i++)
scanf("%s",s[i]+1);
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{ l[i][j]=r[i][j]=j;
if(s[i][j]=='a' || s[i][j]=='w' || s[i][j]=='y' || s[i][j]=='z')
v[i][j]=v[i-1][j]+1;
else
v[i][j]=0;
}
solve();
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{ l[i][j]=r[i][j]=j;
if(s[i][j]=='b' || s[i][j]=='w' || s[i][j]=='x' || s[i][j]=='z')
v[i][j]=v[i-1][j]+1;
else
v[i][j]=0;
}
solve();
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{ l[i][j]=r[i][j]=j;
if(s[i][j]=='c' || s[i][j]=='x' || s[i][j]=='y' || s[i][j]=='z')
v[i][j]=v[i-1][j]+1;
else
v[i][j]=0;
}
solve();
printf("%d\n",ans);
}
}