poj 2185 Milking Grid (最小覆盖子矩形,kmp)
题意:给出一个字符矩形,问一个面积最小的矩形,覆盖掉整个矩形。大概就是二维的最小覆盖子串。
思路:对于每一行做最小覆盖子串,然后求lcm,每一列也是如此。最后记得判断不能超过原有的n,m。
/* ***********************************************
Author :111qqz
Created Time :2016年08月10日 星期三 23时46分47秒
File Name :code/poj/2185.cpp
************************************************ */
1#include <cstdio>
2#include <cstring>
3#include <iostream>
4#include <algorithm>
5#include <vector>
6#include <queue>
7#include <stack>
8#include <set>
9#include <map>
10#include <string>
11#include <cmath>
12#include <cstdlib>
13#include <deque>
14#include <ctime>
15#define fst first
16#define sec second
17#define lson l,m,rt<<1
18#define rson m+1,r,rt<<1|1
19#define ms(a,x) memset(a,x,sizeof(a))
20typedef long long LL;
21#define pi pair < int ,int >
22#define MP make_pair
1using namespace std;
2const double eps = 1E-8;
3const int dx4[4]={1,0,0,-1};
4const int dy4[4]={0,-1,1,0};
5const int inf = 0x3f3f3f3f;
6const int N=1E4+7;
7char s[N][80];
8int n,m;
9int nxt[N];
10void getrownxt(int row,int n)
11{
12 int i = 0 ;
13 int j = -1;
14 nxt[0] = -1;
15 while (i<n)
16 if (j==-1||s[row][i]==s[row][j]) nxt[++i]=++j;
17 else j = nxt[j];
18}
19void getcolnxt(int col,int n)
20{
21 int i = 0 ;
22 int j = -1;
23 nxt[0] = -1;
24 while (i<n)
25 if (j==-1||s[i][col]==s[j][col]) nxt[++i]=++j;
26 else j = nxt[j];
27}
28int gcd( int a,int b)
29{
30 if (a%b==0) return b;
31 return gcd(b,a%b);
32}
33int lcm(int a,int b)
34{
35 return a/gcd(a,b)*b; //蒟蒻的自我修养
36}
37int main()
38{
39 #ifndef ONLINE_JUDGE
40 freopen("code/in.txt","r",stdin);
41 #endif
cin>>n>>m;
for ( int i = 0 ; i < n ; i++) scanf("%s",s[i]);
1 int L = 1;
2 for ( int i = 0 ; i < n ; i++)
3 {
4 getrownxt(i,m);
5 L = lcm(L,m-nxt[m]);
6 }
7 int R = 1;
8 for ( int i = 0 ; i < m ; i++)
9 {
10 getcolnxt(i,n);
11 R = lcm(R,n-nxt[n]);
12 }
1// cout<<"L:"<<L<<" R:"<<R<<endl;
2 L = min(L,m);
3 R = min(R,n);
4 printf("%d\n",L*R);
1 #ifndef ONLINE_JUDGE
2 fclose(stdin);
3 #endif
4 return 0;
5}