1. 程式人生 > >Milking Grid[KMP][最小矩陣覆蓋]

Milking Grid[KMP][最小矩陣覆蓋]

傳送門

橫著跑一遍 , 求出每個的最小公倍數 , 再豎著跑一遍


#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#define M 80
#define N 10050
using namespace std;
string s[N] ;int n,m,lcm1=1,lcm2=1,nxt[N];
int gcd(int a,int b){return !b?a:gcd(b,a%b);}
int Lcm(int a,int b){return a/gcd(a,b)*b;}
int KMP(string s){
	memset(nxt,0,sizeof(nxt));
	for(int i=1,j=0;i<m;i++){
		while(j && s[i]!=s[j]) j = nxt[j-1];
		if(s[i]==s[j]) j++;
		nxt[i] = j;
	}return m - nxt[m-1];
}
int KMP2(int k){
	memset(nxt,0,sizeof(nxt));
	for(int i=1,j=0;i<n;i++){
		while(j && s[i][k]!=s[j][k]) j = nxt[j-1];
		if(s[i][k]==s[j][k]) j++;
		nxt[i] = j;
	}return n - nxt[n-1];
}
int main(){
	scanf("%d%d",&n,&m);
	for(int i=0;i<n;i++){
		cin>>s[i];
		lcm1 = Lcm (lcm1 , KMP(s[i]));
		if(lcm1>=m){lcm1=m;  break;}
	} 
	for(int i=0;i<m;i++){
		lcm2 = Lcm (lcm2 , KMP2(i));
		if(lcm2>=n){lcm2=n;  break;}
	}
	printf("%d",lcm1*lcm2); return 0;
}