poj 2185 Milking Grid(二维KMP+next循环节)

Milking Grid

Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 9708   Accepted: 4230

Description

Every morning when they are milked, the Farmer John's cows form a rectangular grid that is R (1 <= R <= 10,000) rows by C (1 <= C <= 75) columns. As we all know, Farmer John is quite the expert on cow behavior, and is currently writing a book about feeding behavior in cows. He notices that if each cow is labeled with an uppercase letter indicating its breed, the two-dimensional pattern formed by his cows during milking sometimes seems to be made from smaller repeating rectangular patterns. 

Help FJ find the rectangular unit of smallest area that can be repetitively tiled to make up the entire milking grid. Note that the dimensions of the small rectangular unit do not necessarily need to divide evenly the dimensions of the entire milking grid, as indicated in the sample input below. 
 

Input

* Line 1: Two space-separated integers: R and C 

* Lines 2..R+1: The grid that the cows form, with an uppercase letter denoting each cow's breed. Each of the R input lines has C characters with no space or other intervening character. 

Output

* Line 1: The area of the smallest unit from which the grid is formed 

Sample Input

2 5
ABABA
ABABA

Sample Output

2

Hint

The entire milking grid can be constructed from repetitions of the pattern 'AB'.、、

题意:给一个R*C的二维字符矩阵A,然后让你找到一个面积最小的二维矩阵B,满足B循环铺开若干次之后就能得到A。

注意本题中循环铺开也不需要完整循环。例如

ABABA

ABABA

就可以看作是AB在X方向上循环了2.5次,在Y方向上循环了2次得到的。

这道题也是找循环节,允许循环不完整。但是与之前的题目最大的区别是这道题是二维的。解决这道题的关键是意识到二维矩阵的循环实际上在2个维度上是独立的,可以分别计算。

比如我们先处理X方向上的循环节,就可以把矩阵的每一列看成一个“字符“,只不过这个”字符“实际上是一个字符R元组。这样整个矩阵就可以看成是包含C个”字符“的”字符串“。然后我们求这个”字符串“的循环节就可以得到X方向的循环节长度。当然在这种情况下,比较两个”字符“相等的方法是比较两个R元组是不是完全相等。

对于Y方向的循环节也可以用类似的方法:把一行C元组看成一个“字符“,然后在R个”字符“的字符串上找循环节。最后两维的循环节长度相乘就是答案。

#include 
#include 
using namespace std;
const int maxn=10000+10;
int nt[maxn],r,c;
char a[maxn][100];
bool isR(int x,int y)
{
    for (int i=0;i-1&&!isR(k+1,i)) k=nt[k];
            if(isR(k+1,i)) k++;
            nt[i]=k;
        }
        int ans=c-k-1;
        k=-1;
        for (int i=1;i-1&&!isC(k+1,i)) k=nt[k];
            if(isC(k+1,i)) k++;
            nt[i]=k;
        }
        ans*=r-k-1;
        printf("%d\n",ans);
    }
    return 0;
}

 

你可能感兴趣的:(KMP)