Milking Grid 简单KMP

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’.

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<iostream>
#include<algorithm>
using namespace std;
char pos[10010][110];
int pre[10010];
int gcd(int a,int b)
{
    return b>0?gcd(b,a%b):a;
}
int main()
{

 //freopen("in.in","r",stdin);

     int n,m;
     while(~scanf("%d%d",&n,&m))
     {
         for(int i=1;i<=n;i++)
           scanf("%s",pos[i]+1);
         int co=1,ro=1;
         for(int i=1;i<=n;i++)
         {
            pre[0]=0;
            int j=0;
            for(int k=2;k<=m;k++)
            {
                while(j>0&&pos[i][j+1]!=pos[i][k]) j=pre[j];
                if(pos[i][j+1]==pos[i][k]) j++;
                pre[k]=j;
            }

            co=co*(m-pre[m])/gcd(co,m-pre[m]);
         }
        for(int i=1;i<=m;i++)
        {
            pre[0]=0;
            int j=0;
            for(int k=2;k<=n;k++)
            {
                while(j>0&&pos[j+1][i]!=pos[k][i]) j=pre[j];
                if(pos[j+1][i]==pos[k][i]) j++;
                pre[k]=j;
            }
            ro=ro*(n-pre[n])/gcd(ro,n-pre[n]);
        }
        if(co>m) co=m;
        if(ro>n) ro=n;
        //printf("ro=%d co=%d\n",ro,co);
        printf("%d\n",co*ro);
     }
     return 0;
}
/*
 2 9
 accaccacc
 accaccdac
 2 9
 accaccacc
 abcdfsegk
 2 9
 accacacca
 accacacca
*/

    原文作者:KMP算法
    原文地址: https://blog.csdn.net/vickey1018/article/details/21114525
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞