POJ 2185 Milking Grid KMP(矩阵循环节)

                                                        Milking Grid
Time Limit: 3000MS   Memory Limit: 65536K
Total Submissions: 7153   Accepted: 3047

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'.
 
题意:找出矩阵中最小的子矩阵,满足循环它能形成包括原矩阵的矩阵
题解:
       对于每一行,当作一个字符,跑kmp,若有hang[n]!=0 则有循环节,则行最短循环节长度=小矩阵的高=n-hang[n]
    对于列也是如此
//作者:1085422276
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <ctime>
#include <iostream>
#include <algorithm>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <typeinfo>
//#include<bits/stdc++.h>
#include <map>
#include <stack>
typedef long long ll;
using namespace std;
const int inf = ;
inline ll read()
{
ll x=,f=;
char ch=getchar();
while(ch<''||ch>'')
{
if(ch=='-')f=-;
ch=getchar();
}
while(ch>=''&&ch<='')
{
x=x*+ch-'';
ch=getchar();
}
return x*f;
}
ll exgcd(ll a,ll b,ll &x,ll &y)
{
ll temp,p;
if(b==)
{
x=;
y=;
return a;
}
p=exgcd(b,a%b,x,y);
temp=x;
x=y;
y=temp-(a/b)*y;
return p;
}
//*******************************
char mp[][];
int n,m,p[];
int is_equal(int i,int j)
{
for(int k=;k<m;k++)
{
if(mp[i][k]!=mp[j][k])return ;
}
return ;
}
int is_equaf(int i,int j)
{
for(int k=;k<n;k++)
{
if(mp[k][i]!=mp[k][j])return ;
}
return ;
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(p,,sizeof(p));
for(int i=;i<n;i++)
{
scanf("%s",mp[i]);
}
// for(int i=1;i<=n;i++)cout<<mp[i]<<endl;
//return 0;
int j=;
for(int i=;i<m;i++)
{
while(j&&!is_equaf(i,j))j=p[j];
if(is_equaf(i,j))j++;
p[i+]=j;
}
int l;
l=m-(p[m]);
memset(p,,sizeof(p));
j=;
for(int i=;i<n;i++)
{
while(j&&!is_equal(i,j))j=p[j];
if(is_equal(i,j))j++;
p[i+]=j;
}
int r;
r=n-(p[n]);
cout<<l*r<<endl;
}
return ;
}

代码

上一篇:C语言的 32个关键之和9个控制语言之关键字


下一篇:MySQL DBA的个人修养