Largest Submatrix
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 1913 Accepted Submission(s): 912
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
将题目转化后和HDU1505一模一样,没什么好说的
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
//#define LOCAL
using namespace std;
int a[1005][1005];
int b[1005][1005];
int c[1005][1005];
int Left[1005];
int Right[1005];
int main()
{
#ifdef LOCAL
freopen("data.in","r",stdin);
freopen("data.out","w",stdout);
#endif // LOCAL
int m,n;
while(scanf("%d%d",&m,&n)!=EOF){
getchar();
int ch;
int i,j;
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
for(i = 1;i<=m;i++){
for(j = 1;j<=n;j++){
ch = getchar();
if(ch == 'a'||ch == 'y'||ch == 'z'||ch == 'w')
a[i][j] = a[i-1][j] + 1;
if(ch == 'b'||ch == 'w'||ch == 'x'||ch == 'z')
b[i][j] = b[i-1][j] + 1;
if(ch == 'c'||ch == 'x'||ch == 'y'||ch == 'z')
c[i][j] = c[i-1][j] + 1;
}
getchar();
}
memset(Left,0,sizeof(Left));
memset(Right,0,sizeof(Right));
int aMax = 0;
int bMax = 0;
int cMax = 0;
for(i = 1;i<=m;i++){
for(j = 1;j<=n;j++){
Left[j] = j;
while(Left[j]>1&&a[i][Left[j] - 1] >= a[i][j])
Left[j] = Left[Left[j] - 1];
}
for(j = n;j>=1;j--){
Right[j] = j;
while(Right[j]<n&&a[i][Right[j]+1]>=a[i][j])
Right[j] = Right[Right[j] + 1];
}
for(j = 1;j<=n;j++)
if((Right[j] - Left[j] + 1)*a[i][j]>aMax)
aMax = (Right[j] - Left[j] + 1)*a[i][j];
}
for(i = 1;i<=m;i++){
for(j = 1;j<=n;j++){
Left[j] = j;
while(Left[j]>1&&b[i][Left[j] - 1] >= b[i][j])
Left[j] = Left[Left[j] - 1];
}
for(j = n;j>=1;j--){
Right[j] = j;
while(Right[j]<n&&b[i][Right[j]+1]>=b[i][j])
Right[j] = Right[Right[j] + 1];
}
for(j = 1;j<=n;j++)
if((Right[j] - Left[j] + 1)*b[i][j]>bMax)
bMax = (Right[j] - Left[j] + 1)*b[i][j];
}
for(i = 1;i<=m;i++){
for(j = 1;j<=n;j++){
Left[j] = j;
while(Left[j]>1&&c[i][Left[j] - 1] >= c[i][j])
Left[j] = Left[Left[j] - 1];
}
for(j = n;j>=1;j--){
Right[j] = j;
while(Right[j]<n&&c[i][Right[j]+1]>=c[i][j])
Right[j] = Right[Right[j] + 1];
}
for(j = 1;j<=n;j++)
if((Right[j] - Left[j] + 1)*c[i][j]>cMax)
cMax = (Right[j] - Left[j] + 1)*c[i][j];
}
printf("%d\n",max(max(aMax,bMax),cMax));
}
return 0;
}