HDU 2859 Phalanx(对称矩阵 经典dp样例)

传送门:

http://acm.hdu.edu.cn/showproblem.php?pid=2859

Phalanx

Time Limit: 10000/5000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2792    Accepted Submission(s): 1357


Problem Description
Today is army day, but the servicemen are busy with the phalanx for the celebration of the 60th anniversary of the PRC.
A phalanx is a matrix of size n*n, each element is a character (a~z or A~Z), standing for the military branch of the servicemen on that position.
For some special requirement it has to find out the size of the max symmetrical sub-array. And with no doubt, the Central Military Committee gave this task to ALPCs.
A symmetrical matrix is such a matrix that it is symmetrical by the “left-down to right-up” line. The element on the corresponding place should be the same. For example, here is a 3*3 symmetrical matrix:
cbx
cpb
zcc
 

 

Input
There are several test cases in the input file. Each case starts with an integer n (0<n<=1000), followed by n lines which has n character. There won’t be any blank spaces between characters or the end of line. The input file is ended with a 0.
 

 

Output
Each test case output one line, the size of the maximum symmetrical sub- matrix.
 

 

Sample Input
3 abx cyb zca 4 zaba cbab abbc cacq 0
 

 

Sample Output
3 3
 

 

Source
 
题目意思:
给你一个字符矩阵,比如n*n的矩阵,问你最大的对称矩阵的阶数是多少
阶数:比如3*3的矩阵,阶数就是3
对称矩阵的定义:副对角线两边的字符对称,副对角线:从左下到右上
 
分析:
我们从大矩阵的右上角看,每次矩阵阶数加一,都是原来矩阵的下面加一行,左边加一列
给一个2阶的对称矩阵,它对称的字符肯定只有一对
给你一个三阶的对称矩阵,它的最下面的行和最左边的列,对称字符的个数肯定是两对
同理,给一个四阶的对称矩阵,它的最下面的行和最左边的列,对称字符的个数肯定是三对
所以如果该矩阵是对称矩阵的话,随着它阶数的加1,它最下面的行和最左的列的对称字符数也加一
这是后面能dp的原因
 
dp【i】【j】:以i,j为矩阵的左下角,最大对称矩阵的阶数
 
如果当前矩阵i,j的最下一行和最左一列的字符数大于矩阵i-1,j+1的最下一行和最左一列的字符数的话,那么当前矩阵就有可能的对称矩阵(有可能)
所以: dp[i][j]=dp[i-1][j+1]+1;
 
记住:我们是从右上角开始推的,往左下角移动
code:
#include<bits/stdc++.h>
using namespace std;
#define max_v 1005
char a[max_v][max_v];
int dp[max_v][max_v];
int main()
{
    int n;
    while(cin>>n,n)
    {
        memset(dp,0,sizeof(dp));
        getchar();
        for(int i=0;i<n;i++)
        {
            scanf("%s",&a[i]);
            dp[0][i]=1;//初始化
        }
        int ans=1;
        for(int i=1;i<n;i++)
        {
            for(int j=n-1;j>=0;j--)//右上角开始
            {
                int x=i-1,y=j+1;//上一个矩阵的左下角坐标
                int num=1;//对称字符个数
                while(x>=0&&x<n&&y>=0&&y<n&&a[i][y]==a[x][j])//坐标在大矩阵内且字符对称
                {
                    x--;//横坐标上移
                    y++;//纵坐标右移
                    num++;//对称字符数加1
                }
                if(num>dp[i-1][j+1])//判断当前矩阵是不是对称矩阵
                {
                    dp[i][j]=dp[i-1][j+1]+1;
                }else
                {
                    dp[i][j]=num;
                }
                 ans=max(ans,dp[i][j]);//找对称矩阵最大阶
            }
        }
        printf("%d\n",ans);
    }
    return 0;
}

 

posted @ 2018-07-20 20:49  西*风  阅读(479)  评论(1编辑  收藏  举报