POJ2185 Milking Grid(二重KMP)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_42391248/article/details/81874655

Milking Grid

Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 9905   Accepted: 4304

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'.

扫描二维码关注公众号,回复: 2964160 查看本文章

题意很难理解,下面列出几个数据自己感觉着理解吧。

ABABA     
ABABA                                        
2                 
(AB)            
ABCABCAB
BCABCABC         
6  
(ABC
BCA)
ABCDEFAB
AAAABAAA    
12
(ABCDEF
AAAABA)

题解:分别求出行的最小循环长度和列的最小循环长度,然后相乘就答案。求行的最小循环长度时,把一列看成一个整体,求出next[i],len-next[len]就是最小循环长度,同理求列。

具体代码如下:

#include<iostream>
#include<string>
#include<vector>
using namespace std;
int r,c;
vector<string> s;
bool strcmp_c(int a,int b)
{
	for(int i=0;i<r;i++)
		if(s[i][a]!=s[i][b])
			return 0;
	return 1;
}
bool strcmp_r(int a,int b)
{
	for(int i=0;i<c;i++)
		if(s[a][i]!=s[b][i])
			return 0;
	return 1;
}
int getnext_c()
{
	int next[100];
	int i=-1,j=0;
	next[0]=-1;
	while(j<c)
		if(i==-1||strcmp_c(i,j))	
			next[++j]=++i;
		else
			i=next[i];
	return c-next[c];
}
int getnext_r()
{
	int next[10005];
	int i=-1,j=0;
	next[0]=-1;
	while(j<r)
		if(i==-1||strcmp_r(i,j))	
			next[++j]=++i;
		else
			i=next[i];
	return r-next[r];
}
int main()
{
	while(cin>>r>>c)
	{		
		for(int i=0;i<r;i++)
		{
			string a;
			cin>>a;
			s.push_back(a);
		}
		cout<<getnext_c()*getnext_r()<<endl;	
                s.clear();	
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42391248/article/details/81874655
今日推荐