Largest Submatrix(动态规划)

时间:2022-04-12 16:29:16

Largest Submatrix

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 2018    Accepted Submission(s): 967

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

题解:

上题 的加强版。

三种情况。

全部变为a,全部为b,全部为c,分别求最大。

代码:

 #include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
using namespace std;
const int INF=0x3f3f3f3f;
#define mem(x,y) memset(x,y,sizeof(x))
#define SI(x) scanf("%d",&x)
#define PI(x) printf("%d",x)
#define SD(x,y) scanf("%lf%lf",&x,&y)
#define P_ printf(" ")
const int MAXN=;
typedef long long LL;
int dp[][MAXN][MAXN],s[MAXN],l[MAXN],r[MAXN];
char mp[MAXN][MAXN];
bool isa(char ch){
if(ch=='a'||ch=='w'||ch=='y'||ch=='z')
return true;
else return false;
}
bool isb(char ch){
if(ch=='b'||ch=='w'||ch=='x'||ch=='z')
return true;
else return false;
}
bool isc(char ch){
if(ch=='c'||ch=='x'||ch=='y'||ch=='z')
return true;
else return false;
} int main(){
int N,M;
while(~scanf("%d%d",&N,&M)){
for(int i=;i<=N;i++)
scanf("%s",mp[i]+);
mem(dp,);
int ans=;
for(int i=;i<=N;i++){
for(int j=;mp[i][j];j++){
if(isa(mp[i][j]))dp[][i][j]=dp[][i-][j]+;
s[j]=dp[][i][j];l[j]=j;r[j]=j;
}
s[]=s[M+]=-;
for(int j=;j<=M;j++){
while(s[l[j]-]>=s[j])
l[j]=l[l[j]-];
}
for(int j=M;j>=;j--){
while(s[r[j]+]>=s[j])
r[j]=r[r[j]+];
}
for(int j=;j<=M;j++){
ans=max((r[j]-l[j]+)*s[j],ans);
}
//
for(int j=;mp[i][j];j++){
if(isb(mp[i][j]))dp[][i][j]=dp[][i-][j]+;
s[j]=dp[][i][j];l[j]=j;r[j]=j;
}
s[]=s[M+]=-;
for(int j=;j<=M;j++){
while(s[l[j]-]>=s[j])
l[j]=l[l[j]-];
}
for(int j=M;j>=;j--){
while(s[r[j]+]>=s[j])
r[j]=r[r[j]+];
}
for(int j=;j<=M;j++){
ans=max((r[j]-l[j]+)*s[j],ans);
}
//
for(int j=;mp[i][j];j++){
if(isc(mp[i][j]))dp[][i][j]=dp[][i-][j]+;
s[j]=dp[][i][j];l[j]=j;r[j]=j;
}
s[]=s[M+]=-;
for(int j=;j<=M;j++){
while(s[l[j]-]>=s[j])
l[j]=l[l[j]-];
}
for(int j=M;j>=;j--){
while(s[r[j]+]>=s[j])
r[j]=r[r[j]+];
}
for(int j=;j<=M;j++){
ans=max((r[j]-l[j]+)*s[j],ans);
}
}
printf("%d\n",ans);
}
return ;
}