HDU 2870 Largest Submatrix

Largest Submatrix

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

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
 
Recommend
gaojie
 
 
 
 
#include<stdio.h>
#include<string.h>

const int maxn=1010;

char str[maxn][maxn];
int dp[maxn][maxn];
int m,n,ans,l[maxn],r[maxn];

void Solve(){
    int i,j;
    for(i=1;i<=m;i++){
        dp[i][0]=dp[i][n+1]=-1;
        for(j=1;j<=n;j++){
            l[j]=j;
            while(dp[i][j]<=dp[i][l[j]-1])
                l[j]=l[l[j]-1];
        }
        for(j=n;j>=1;j--){
            r[j]=j;
            while(dp[i][j]<=dp[i][r[j]+1])
                r[j]=r[r[j]+1];
        }
        for(j=1;j<=n;j++)
            if(ans<(r[j]-l[j]+1)*dp[i][j])
                ans=(r[j]-l[j]+1)*dp[i][j];
    }
}

int main(){

    //freopen("input.txt","r",stdin);

    memset(dp,0,sizeof(dp));
    while(scanf("%d%d",&m,&n)!=EOF){
        //getchar();
        int i,j;
        ans=0;
        for(i=1;i<=m;i++)
            scanf("%s",str[i]+1);
        //for(i=1;i<=m;i++)
            //printf("%s\n",str[i]+1);
        //printf("m=%d n=%d\n",m,n);
        for(i=1;i<=m;i++)
            for(j=1;j<=n;j++){
                if(str[i][j]=='a' || str[i][j]=='w' || str[i][j]=='y' || str[i][j]=='z')
                    dp[i][j]=dp[i-1][j]+1;
                else
                    dp[i][j]=0;
            }
        //printf("m=%d n=%d\n",m,n);
        Solve();
        //printf("m=%d n=%d\n",m,n);
        for(i=1;i<=m;i++)
            for(j=1;j<=n;j++){
                if(str[i][j]=='b' || str[i][j]=='w' || str[i][j]=='x' || str[i][j]=='z')
                    dp[i][j]=dp[i-1][j]+1;
                else
                    dp[i][j]=0;
            }
        Solve();
        for(i=1;i<=m;i++)
            for(j=1;j<=n;j++){
                if(str[i][j]=='c' || str[i][j]=='x' || str[i][j]=='y' || str[i][j]=='z')
                    dp[i][j]=dp[i-1][j]+1;
                else
                    dp[i][j]=0;
            }
        Solve();
        printf("%d\n",ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/jackge/p/2980706.html