问题描述:
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 wxyzSample Output
3
题目题意:题目给了一个矩阵,其中w,x,y,z可以去替换成a,b,c其中几个,问最大一个子矩阵(全部都是相同的字符)的面积。
题目分析:最大子矩阵的题意,但是替换比较麻烦,所以我们要先固定字符,我们假设我们求得最大子矩阵的字符都是'a',接下来就好办了,因为字符已经确定了,所以我们预处理dp数组的时候,只需要确定能否接在'a'后面就可以了,同理处理其他字符'b','c'
代码如下:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
using namespace std;
const int maxn=1e3+10;
char G[maxn][maxn];
int dp[maxn][maxn],area,n,m;
void get_area()//求最大子矩阵
{
for (int i=1;i<=n;i++) {
int left[maxn],right[maxn],t;
left[1]=1;right[m]=m;
for (int j=2;j<=m;j++) {
t=j;
while (t>1&&dp[i][j]<=dp[i][t-1])
t=left[t-1];
left[j]=t;
}
for (int j=m-1;j>=1;j--) {
t=j;
while (t<m&&dp[i][j]<=dp[i][t+1])
t=right[t+1];
right[j]=t;
}
for (int j=1;j<=m;j++) {
area=max(area,(right[j]-left[j]+1)*dp[i][j]);
}
}
}
int main()
{
while (scanf("%d%d",&n,&m)!=EOF) {
for (int i=1;i<=n;i++) {
scanf("%s",G[i]+1);
}
area=0;
memset (dp,0,sizeof (dp));
for (int j=1;j<=m;j++) {//处理'a'
for (int i=n;i>=1;i--) {
if (G[i][j]=='a'||G[i][j]=='w'||G[i][j]=='y'||G[i][j]=='z') dp[i][j]=dp[i+1][j]+1;
else dp[i][j]=0;
}
}
get_area();
memset (dp,0,sizeof (dp));
for (int j=1;j<=m;j++) {//处理'b'
for (int i=n;i>=1;i--) {
if (G[i][j]=='b'||G[i][j]=='w'||G[i][j]=='x'||G[i][j]=='z') dp[i][j]=dp[i+1][j]+1;
else dp[i][j]=0;
}
}
get_area();
memset (dp,0,sizeof (dp));
for (int j=1;j<=m;j++) {//处理'c'
for (int i=n;i>=1;i--) {
if (G[i][j]=='c'||G[i][j]=='x'||G[i][j]=='y'||G[i][j]=='z') dp[i][j]=dp[i+1][j]+1;
else dp[i][j]=0;
}
}
get_area();
printf("%d\n",area);
}
return 0;
}