POJ2185Milking Grid(最小覆盖子串 + 二维KMP)

题意: 一个r*c的矩形,求一个子矩形通过平移复制能覆盖整个矩形

关于一个字符串的最小覆盖子串可以看这里http://blog.csdn.net/fjsd155/article/details/6866991

把他分成对行和对列,对行覆盖最小就是n - next[n] ,然后求最小公倍数

对列的也是n - next[n], 然后求最小公倍数

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int Max = 100000 + 10;
char str[Max][100];
int Next[Max];
int r, c;
int getNextc(int n)
{
    int k = -1;
    Next[0] = -1;
    int i = 0;
    while (i < c)
    {
        while (k != -1 && str[n][i] != str[n][k])
            k = Next[k];
        Next[++i] = ++k;
    }
    return c - Next[c];  // 是 c - Next[c],next[c]才是整个串 最长(前缀 == 后缀)
}
int getNextr(int n)
{
    int k = -1;
    Next[0] = -1;
    int i = 0;
    while (i < r)
    {
        while (k != -1 && str[i][n] != str[k][n])
            k = Next[k];
        Next[++i] = ++k;
    }
    return r - Next[r];
}
int gcd(int a, int b)
{
    if (a == 0)
        return b;
    return gcd(a % b, a);
}
int getNum(int a, int b)
{
    if (a > b)
        swap(a, b);
    int d = gcd(a, b);
    return a / d * b;
}
int main()
{

    while (scanf("%d%d", &r, &c) != EOF)
    {
        getchar();
        for (int i = 0; i < r; i++)
            scanf("%s", str[i]);
        int ans1 = 1, ans2 = 1;
        for (int i = 0; i < r; i++)  // 按行处理
        {
            memset(Next, 0, sizeof(Next));
            ans1 = getNum(ans1, getNextc(i));
            if (ans1 >= c)
            {
                ans1 = c;
                break;
            }
        }
        for (int i = 0; i < c; i++)
        {
            memset(Next, 0, sizeof(Next));
            ans2 = getNum(ans2, getNextr(i));
            if (ans2 >= r)
            {
                ans2 = r;
                break;
            }
        }
        printf("%d\n", ans1 * ans2);
    }
    return 0;
}

  

 

posted @ 2016-04-15 11:18  zhaop  阅读(249)  评论(0编辑  收藏  举报