POJ 2185 Milking Grid

Milking Grid

Time Limit: 3000ms
Memory Limit: 65536KB
This problem will be judged on PKU. Original ID: 2185
64-bit integer IO format: %lld      Java class name: Main
 
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,两次KMP,求最小循环节的乘积。
 
 

Source

 
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <cmath>
 5 #include <algorithm>
 6 #include <climits>
 7 #include <vector>
 8 #include <queue>
 9 #include <cstdlib>
10 #include <string>
11 #include <set>
12 #include <stack>
13 #define LL long long
14 #define pii pair<int,int>
15 #define INF 0x3f3f3f3f
16 using namespace std;
17 int row,col,fail[10100],x,y;
18 char str[10010][80];
19 bool cmp(int a,int b){
20     for(int i = 0; i < row; i++)
21         if(str[i][a] != str[i][b]) return false;
22         return true;
23 }
24 int main() {
25     while(~scanf("%d %d",&row,&col)){
26         for(int i = 0; i < row; i++)
27             scanf("%s",str[i]);
28         fail[0] = fail[1] = 0;
29         for(int i = 1; i < row; i++){
30             int j = fail[i];
31             while(j && strcmp(str[i],str[j])) j = fail[j];
32             if(!strcmp(str[i],str[j])) fail[i+1] = j+1;
33             else fail[i+1] = 0;
34         }
35         x = row - fail[row];
36         fail[0] = fail[1] = 0;
37         for(int i = 1; i < col; i++){
38             int j = fail[i];
39             while(j && !cmp(i,j)) j = fail[j];
40             if(cmp(i,j)) fail[i+1] = j+1;
41             else fail[i+1] = 0;
42         }
43         y = col - fail[col];
44         printf("%d\n",x*y);
45     }
46     return 0;
47 }
View Code

 

posted @ 2014-09-18 22:21  狂徒归来  阅读(206)  评论(0编辑  收藏  举报