HDU - 2859 Phalanx (dp_最大對稱子圖)

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

題意:

求最大對稱子圖(關於反對角線對稱)

dp[ i ][ j ] 表示以 (i, j) 爲左下角的最大對稱子圖,必須包含該點

每次向上向下查找最大匹配數,如果大於右上角的dp值,那麼就是右上角的dp值 + 1,因爲如果再多的話內一層會不再匹配。

如果小於右上角的dp值,那麼就是該點的最大匹配數,因爲如果再多的話外層會不再匹配

左邊是第一種情況,右邊是第二種情況,紅色框表示該點的最大對稱子圖

                      

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const ll mod = 1e9 + 7;
const double eps = 1e-8;
const int N = 1e3 + 10;

int dp[N][N];   ///dp[i][j]:以(i, j)爲左下角的最大對稱矩陣,必須包括(i, j)
char s[N][N];

int main()
{
    int n;
    while(~scanf("%d", &n) && n)
    {
        for(int i = 1; i <= n; ++i)
        {
            scanf("%s", s[i] + 1);
        }
        int maxx = 0;
        for(int i = 1; i <= n; ++i)
        {
            for(int j = 1; j <= n; ++j)
            {
                if(i == 1 || j == n)    ///每個字母都算一個
                {
                    dp[i][j] = 1;
                }
                int x = i;
                int y = j;
                while(x >= 1 && y <= n && s[x][j] == s[i][y])   ///從(i, j)向上向右找最大匹配的數量
                {
                    x--;
                    y++;
                }
                int cnt = i - x;    ///最大匹配數量
                if(cnt > dp[i - 1][j + 1])              ///超過了以(i - 1, j + 1)爲左下角的最大對稱矩陣
                {
                    dp[i][j] = dp[i - 1][j + 1] + 1;    ///最多也就延伸到dp[i - 1][j + 1] + 1;(向左下方擴展了一行)
                }
                else
                {
                    dp[i][j] = cnt;
                }
                maxx = max(maxx, dp[i][j]);
            }
        }
        cout<<maxx<<'\n';
    }
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章