Milking Grid
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 7896 | Accepted: 3408 |
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'.
利用KMP求行和列的最小循环节,并找出它们的最小公倍数,行和列相乘即为答案。
//2016.8.17
#include<iostream>
#include<cstdio>
#include<algorithm> using namespace std; const int N = ;
const int M = ;
char grid[N][M];
int nex[N]; int gcd(int a, int b)
{
return b==?a:gcd(b, a%b);
} int lcm(int a, int b)
{
return a/gcd(a, b)*b;
} void getNext(int pos, int n, int fg)//构造next[]数组,fg为标记,0为行,1为列
{
nex[] = -;
for(int i = , fail = -; i < n;)
{
if(fg == && (fail == - || grid[pos][i] == grid[pos][fail]))
{
i++, fail++;
nex[i] = fail;
}else if(fg == && (fail == - || grid[i][pos] == grid[fail][pos]))
{
i++, fail++;
nex[i] = fail;
}else fail = nex[fail];
}
} int main()
{
int n, m, clen, rlen;
while(scanf("%d%d", &n, &m)!=EOF)
{
clen = rlen = ;
for(int i = ; i < n; i++)
scanf("%s", grid[i]);
for(int i = ; i < n; i++)//用最小公倍数找到循环块的宽度
{
getNext(i, m, );
rlen = lcm(rlen, m-nex[m]);//m-nex[m]为该行最小循环节的长度
if(rlen>=m){
rlen = m; break;
}
}
for(int i = ; i < m; i++)//用最小公倍数找到循环块的高度
{
getNext(i, n, );
clen = lcm(clen, n-nex[n]);//n-nex[n]为该列最小循环节的长度
if(clen>=n){
clen = n; break;
}
}
printf("%d\n", clen*rlen);
}
return ;
}