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);
}
}

本文介绍了一种通过使用单调栈解决最大相同子矩阵问题的方法。该问题涉及在一个由特定字符组成的矩阵中,允许某些字符转换为其他字符后,寻找最大的全由相同字母构成的子矩阵。文中提供了一个C++实现示例,展示了如何通过迭代和更新矩阵来找到符合条件的最大子矩阵。
2826

被折叠的 条评论
为什么被折叠?



