Largest Submatrix
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2570 Accepted Submission(s): 1262
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
POINT:
用的单调栈,还有一种方法是求上界和下界。
#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <stack>
using namespace std;
#define LL long long
const int N = 1000;
char mp[N+3][N+3];
int a[N+3][N+3];
int n,m;
int ans;
void doit()
{
for(int j=1;j<=m;j++)
{
stack<int>q;
int pos[N+3];
for(int i=1;i<=n;i++)
{
pos[i]=i;
while(!q.empty()&&a[i][j]<=a[q.top()][j])
{
ans=max(ans,a[q.top()][j]*(i-pos[q.top()]));
pos[i]=pos[q.top()];
q.pop();
}
q.push(i);
}
while(!q.empty())
{
ans=max(ans,a[q.top()][j]*(n-pos[q.top()]+1));
q.pop();
}
}
}
int main()
{
while(~scanf("%d %d",&n,&m))
{
ans=0;
for(int i=1;i<=n;i++)
{
scanf("%s",mp[i]+1);
}
for(int i=1;i<=n;i++)
{
int now=0;
for(int j=1;j<=m;j++)
{
if(mp[i][j]=='a'||mp[i][j]=='w'||mp[i][j]=='y'||mp[i][j]=='z')
now++;
else now=0;
a[i][j]=now;
}
}
// for(int i=1;i<=n;i++)
// {
// for(int j=1;j<=m;j++)
// {
// printf("%d ",a[i][j]);
// }
// printf("\n");
// }
doit();
for(int i=1;i<=n;i++)
{
int now=0;
for(int j=1;j<=m;j++)
{
if(mp[i][j]=='b'||mp[i][j]=='w'||mp[i][j]=='x'||mp[i][j]=='z')
now++;
else now=0;
a[i][j]=now;
}
}
doit();
for(int i=1;i<=n;i++)
{
int now=0;
for(int j=1;j<=m;j++)
{
if(mp[i][j]=='c'||mp[i][j]=='x'||mp[i][j]=='y'||mp[i][j]=='z')
now++;
else now=0;
a[i][j]=now;
}
}
doit();
printf("%d\n",ans);
}
}