Milking Grid
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 6829 | Accepted: 2903 |
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.
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.
* 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
给定一个由字符组成的矩阵,求出它的面积最小的覆盖矩阵。
最小覆盖矩阵类似于最小覆盖子串,只不过是扩展到二维而已。
最小覆盖子串必定是原串的前缀,对于矩阵,可以求出每一行的最小覆盖子串的长度,只要对这些长度求最小公倍数,就可以获得最小覆盖矩阵的宽度。
同理,求出每一列的最小覆盖子串的长度,再求最小公倍数,就可以获得最小覆盖矩阵的高度了。
这里有一个地方要注意,如果求最小公倍数的过程中发现“行最小公倍数>=原矩阵宽度“时,可以确定最小覆盖矩阵的宽度与原矩阵一样。列也是一样的道理。因为原矩阵必定是它自己的覆盖矩阵。
以上转自网络
最小覆盖子串(串尾多一小段时,用前缀覆盖)长度为n-next[n],n为串长。这点不是太明白。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int r,c;
int next[11000];
char map[11000][110];
int gcd(int a,int b){
if(b == 0)
return a;
else
return gcd(b, a % b);
}
int gdc(int a,int b){
return a * b / gcd(a,b);
}
void kmpc(int k){
int i = 0, j = -1;
next[0] = -1;
while (i < c){
if (j == -1 || map[k][i] == map[k][j]){
++i;
++j;
next[i] = j;
}
else j = next[j];
}
}
void kmpr(int k){
int i = 0, j = -1;
next[0] = -1;
while(i < r){
if (j == -1 || map[i][k] == map[j][k]){
++i;
++j;
next[i] = j;
}
else j = next[j];
}
}
int main(){
scanf("%d%d", &r, &c);
int i,j;
for (i = 0; i < r; ++i)
scanf("%s", map[i]);
int num1 = 1;
int num2 = 1;
for(i = 0; i < r; ++i){
kmpc(i);
num1 = gdc(num1, c - next[c]);
if (num1 > c){
num1 = c;
break;
}
}
for(i = 0; i < c; ++i){
kmpr(i);
num2 = gdc(num2, r - next[r]);
if(num2 > r){
num2 = r;
break;
}
}
printf("%d\n", num1 * num2);
return 0;
}