hdu2870—Largest Submatrix(dp)

Largest Submatrix

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


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 4abcwwxyz
 
Sample Output
 
  
3


解题思路:和hdu1505,hdu1506差不多

这里我们将矩阵字符全部变成‘a’,‘b’或‘c’,单独求其最大子矩阵。


#include <iostream>
#include <stack>
#include <vector>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>

using namespace std;

const int N = 1010;
const int INF = 0x3fffffff;

struct Node{
    int id,val;
    Node(){}
    Node(int _id,int _v){
        id = _id; val = _v;
    }
}Stack[N];

int H[N],L[N],R[N],M[N][N],n,m;
char data[N][N];

void deal()
{
    int tail;
    Stack[0] = Node(0,-1);
    tail = 0;
    for(int i = 0; i < m; ++i){
        while(tail != 0 && H[i] <= Stack[tail].val) tail--;
        L[i] = Stack[tail].id+1;
        Stack[++tail] = Node(i+1,H[i]);
    }
    Stack[0] = Node(m+1,-1);
    tail = 0;
    for(int i = m-1; i >= 0; --i){
        while(tail != 0 && H[i] <= Stack[tail].val) tail--;
        R[i] = Stack[tail].id-1;
        Stack[++tail] = Node(i+1,H[i]);
    }
}

int solve()
{
    memset(H,0,sizeof(H));
    int ans = 0;
    for(int i = 0; i < n; ++i){
        for(int j = 0; j < m; ++j)
            if(M[i][j] == 1) H[j]++;
            else H[j] = 0;
        deal();
        for(int j = 0; j < m; ++j){
            ans = max(ans,H[j]*(R[j]-L[j]+1));
        }
    }
    return ans;
}

void Change(char c1,char c2,char c3,char c4)
{
    for(int i = 0; i < n; ++i){
        for(int j = 0; j < m; ++j){
            if(data[i][j] == c1 || data[i][j] == c2 || data[i][j] == c3 || data[i][j] == c4)
                M[i][j] = 1;
            else
                M[i][j] = 0;
        }
    }
}

int main()
{
    while(~scanf("%d%d",&n,&m)){
        for(int i = 0; i < n; ++i) scanf(" %s",data[i]);
        int ans = 0;

        //全部变成‘a’
        Change('a','w','y','z');
        ans = max(ans,solve());

        //全部变成‘b’
        Change('b','w','x','z');
        ans = max(ans,solve());

        //全部变成‘c’
        Change('c','x','y','z');
        ans = max(ans,solve());

        printf("%d\n",ans);
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/jiangzhiyuan123/article/details/80055977