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.Input
* Line 1: Two space-separated integers: R and COutput
* Line 1: The area of the smallest unit from which the grid is formedSample Input
2 5 ABABA ABABA
Sample Output
2題意:r*c的字符串,問用最小的面積的字符串去覆蓋它,求最小的面積 思路:可以分行分列考慮,容易想到當只考慮行的時候,只要把每一行看成一個字符,就可以求出關於行的next數組,然後求出最短的循環串 r-next[r] ,列也是如此,所以最終答案就是 (c-P[c])*(r-F[r]) P,F分別為各自的next數組。
#include#include #include #include #include #include #include using namespace std; const int maxn = 10000+10; const int maxm = 80; char mat[maxn][maxm]; char revmat[maxm][maxn]; int r,c; int P[maxn],F[maxn]; int gcd(int a,int b) { if(b==0) return a; else return gcd(b,a%b); } void getP() { P[1] = P[0] = 0; for(int i = 1; i < r; i++) { int j = P[i]; while(j && strcmp(mat[i],mat[j])) j = P[j]; if(strcmp(mat[i],mat[j])==0) P[i+1] = j+1; else P[i+1] = 0; } } void getF() { F[1] = F[0] = 0; for(int i = 1; i < c; i++) { int j = F[i]; while(j && strcmp(revmat[i],revmat[j])) j = F[j]; if(strcmp(revmat[i],revmat[j])==0) F[i+1] = j+1; else F[i+1] = 0; } } void getRev() { for(int i = 0; i < c; i++) { for(int j = 0; j < r; j++) { revmat[i][j] = mat[j][i]; } } } void solve() { int L = r-P[r],R = c - F[c]; printf("%d\n",L*R); } int main(){ while(~scanf("%d%d",&r,&c)){ for(int i = 0; i < r; i++) scanf("%s",mat[i]); getP(); getRev(); getF(); solve(); } return 0; }