Time Limit: 2000/1000 MS (Java/Others)
Memory Limit: 32768/32768 K (Java/Others)
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
Source
2009 Multi-University Training Contest 7 - Host by FZU
题意:
给一个字符组成的n*m的矩阵,其中’w’可以变成’a’或者’b’,‘x’可以变成’b’或者’c’,‘y’可以变成’a’或者’c’,‘z’可以变成’a’或者’b’或者’c’,找到一个矩阵使得这个矩阵中的字符都一样,问这个矩阵面积最大的是多少。
题解:
我们可以分成三个小问题讨论,分别考虑全a矩阵,全b矩阵,全c矩阵的最大面积。
such as 对于字符’a’考虑:
考虑每一行,
f
[
i
]
[
j
]
f[i][j]
f[i][j]记为在第
j
j
j列,以第
i
i
i行为结尾的最长的连续字符’a’的长度是多少
可以
O
(
n
∗
m
)
O(n*m)
O(n∗m)预处理
f
[
i
]
[
j
]
f[i][j]
f[i][j]
然后对于每一行来说我们记录一个
l
[
j
]
l[j]
l[j]和一个
r
[
j
]
r[j]
r[j]表示在不影响列字符长度
f
[
i
]
[
j
]
f[i][j]
f[i][j]的大小的情况下,以
j
j
j为扩张起点,往右和往左最远可以扩张到的边界。这个对于每一个
i
i
i来说可以
O
(
m
)
O(m)
O(m)求得。
对于第
i
i
i行来说最大相同字符矩阵面积就是
m
a
x
(
f
[
i
]
[
j
]
∗
(
r
[
j
]
−
l
[
j
]
+
1
)
)
max(f[i][j]*(r[j]-l[j]+1))
max(f[i][j]∗(r[j]−l[j]+1))
#include<bits/stdc++.h>
#define LiangJiaJun main
using namespace std;
int n,m,f[1004][1004];
char mp[1004][1004];
int l[1004],r[1004];
int dp(char a,char b,char c,char d){
int ans=0;
memset(f,0,sizeof(f));
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
if(mp[i][j]==a||mp[i][j]==b||mp[i][j]==c||mp[i][j]==d){
f[i][j]=f[i-1][j]+1;
}
else f[i][j]=0;
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
l[j]=j;
r[j]=j;
}
f[i][0]=-1;
f[i][m+1]=-1;
for(int j=1;j<=m;j++){
while(f[i][j]<=f[i][l[j]-1])l[j]=l[l[j]-1];
}
for(int j=m;j>=1;j--){
while(f[i][j]<=f[i][r[j]+1])r[j]=r[r[j]+1];
}
for(int j=1;j<=m;j++){
ans=max(ans,f[i][j]*(r[j]-l[j]+1));
}
}
return ans;
}
int w33ha(){
for(int i=1;i<=n;i++)scanf("%s",mp[i]+1);
printf("%d\n",max(dp('a','w','y','z'),max(dp('b','w','x','z'),dp('c','x','y','z'))));
return 0;
}
int LiangJiaJun(){
while(scanf("%d%d",&n,&m)!=EOF)w33ha();
return 0;
}