Milking Grid
Time Limit:3000MS |
| Memory Limit:65536K |
Total Submissions:4024 |
| Accepted:1647 |
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>
const int maxr = 10001;
const int maxc = 76;
int next[maxr];
struct Str
{
int n, m;
char mat[maxr][maxc];
} s;
void get_row_next(Str s, int next[], int r)
{ // 求第r行的next值
int i = 0, j = next[0] = -1;
while (i < s.m)
{
if (j == -1 || s.mat[r][i] == s.mat[r][j])
next[++i] = ++j;
else
j = next[j];
}
} // get_roe_next
void get_col_next(Str s, int next[], int c)
{ // 求第c列的next值
int i = 0, j = next[0] = -1;
while (i < s.n)
{
if (j == -1 || s.mat[i][c] == s.mat[j][c])
next[++i] = ++j;
else
j = next[j];
}
} // get_col_next
int lcm (int a, int b)
{ int t;
if (a < b) a ^= b, b ^= a, a ^= b; t = a;
while (b&&a % b != 0) a += t;
return a;
} /// lcm
int main()
{
int i, j, a, b;
scanf("%d %d", &s.n, &s.m);
for (i = 0; i < s.n; i++) scanf("%s", s.mat[i]);
for (i = b = 0; i < s.n; i++)
{
get_row_next(s, next, i);
a = s.m - next[s.m];
b = lcm(a, b);
if (b >= s.m ){ b = s.m; break; }
} // for_i
for (i = b, j = b = 0; j < s.m; j++)
{
get_col_next(s, next, j);
a = s.n - next[s.n];
b = lcm(a, b);
if (b >= s.n ){ b = s.n; break; }
} //for_j
a = i * b; b = s.m * s.n;
printf("%d\n", a > b ? b:a );
//} // while
return 0;
}