380 字
2 分钟
POJ 2185 Milking Grid
2017-07-03

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

题解#

要求循环节,想到”POJ 2406 Power Strings”
把情况拓展到二维
对于每一个横行求最短循环节也就是m-next[m]
然后不断的求lcm
竖列也是一样
最后乘起来就可以了
不过在求lcm时如果大于边界就可以将他的值给为边界

/*
 * @Author: WildRage 
 * @Date: 2017-07-01 10:17:47 
 * @Last Modified by: WildRage
 * @Last Modified time: 2017-07-01 11:08:00
 */
#include<iostream>
#include<cstdio>
#include<cstring>
namespace MineWorkSpace{
	char s[10005][80];
	int next[10005][80];
	int next2[80][10005];
	int gcd(int a,int b){
		return b==0? a: gcd(b,a%b);
	}
	int lcm(int a,int b){
		return a/gcd(a,b)*b;
	}
	int Main()
	{
	#ifdef Mine
	    freopen("mgrid.in","r",stdin);
	    freopen("mgrid.out","w",stdout);
	#endif
		int n,m;
		scanf("%d%d",&n,&m);
		for(int i=0;i<n;i++){
			scanf("%s",s[i]);
		}
		int ans1=1,ans2=1;
		for(int i=0;i<n;i++){
			int j=0,k=-1;
			next[i][0]=-1;
			while(j<m){
				if(k==-1||s[i][j]==s[i][k]){
					next[i][++j]=++k;
				}
				else k=next[i][k];
			}
			if(m-next[i][m]) ans1=lcm(ans1,m-next[i][m]);
			if(ans1>m)ans1=m;
		}
		for(int i=0;i<m;i++){
			int j=0,k=-1;
			next2[i][0]=-1;
			while(j<n){
				if(k==-1||s[j][i]==s[k][i]){
					next2[i][++j]=++k;
				}
				else k=next2[i][k];
			}
			if(n-next2[i][n])ans2=lcm(ans2,n-next2[i][n]);
			if(ans2>n)ans2=n;
		}
		return printf("%d",ans1*ans2);
	}
}
int main()
{
	MineWorkSpace::Main();
	//while(1);
}

POJ 2185 Milking Grid
https://www.nekomio.com/posts/26/
作者
NekoMio
发布于
2017-07-03
许可协议
CC BY-NC-SA 4.0