hdu 简单DP 1011 Largest Submatrix

Largest Submatrix

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 32768/32768K (Java/Other)
Total Submission(s) : 39   Accepted Submission(s) : 16

Font: Times New Roman | Verdana | Georgia

Font Size:  

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

//枚举三种状态,变成类似于木棍求面积的问题,用了o(n^3)的方法,也可以用单调栈o(n^2)
#include <bits/stdc++.h>
using namespace std;
int n,m,ans;
char a[1005][1005];
int h[1005][1005],l[1005],r[1005];
void DP()
{
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            l[j]=r[j]=j;//初始化左右边
        }
        h[i][0]=h[i][m+1]=-1;
        for(int j=1;j<=m;j++)
        {
            while(h[i][l[j]-1]>=h[i][j]) //当左边的比自己的高,更新l
                l[j]=l[l[j]-1];
        }
        for(int j=m;j>=1;j--)
        {
            while(h[i][r[j]+1]>=h[i][j]) //当右边的比自己高,更新r
                r[j]=r[r[j]+1];
        }
        for(int j=1;j<=m;j++)
            ans=max(ans,(r[j]-l[j]+1)*h[i][j]); //宽度*高度为面积,更新、ans
    }
}
int main()
{
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        ans=-1;
        for(int i=1;i<=n;i++)
        {
            scanf("%s",a[i]+1);
        }
        memset(h,0,sizeof(h));
        for(int i=1;i<=n;i++) //枚举全为a
        {
            for(int j=1;j<=m;j++)
            {
                char q=a[i][j];
                if(q=='a'||q=='w'||q=='y'||q=='z')
                {
                    h[i][j]=h[i-1][j]+1;//得到每一个数,列上字母最大的相同数
                }
            }
        }
        DP();
        memset(h,0,sizeof(h));
        for(int i=1;i<=n;i++) //枚举全为b
        {
            for(int j=1;j<=m;j++)
            {
                char q=a[i][j];
                if(q=='b'||q=='w'||q=='x'||q=='z')
                {
                    h[i][j]=h[i-1][j]+1;
                }
            }
        }
        DP();
        memset(h,0,sizeof(h));
        for(int i=1;i<=n;i++)  //枚举全为c
        {
            for(int j=1;j<=m;j++)
            {
                char q=a[i][j];
                if(q=='c'||q=='x'||q=='y'||q=='z')
                {
                    h[i][j]=h[i-1][j]+1;
                }
            }
        }
        DP();
        printf("%d\n",ans);
    }
    return 0;
}













猜你喜欢

转载自blog.csdn.net/qq_41037114/article/details/81006088