[poj 2185] Milking Grid 解题报告(KMP+最小循环节)

本文提供了一种解决POJ 2185问题的有效算法,通过KMP算法找到矩阵中每行和每列的最小重复单元,然后计算这些单元的最小公倍数,以确定构成整个矩阵的最小重复矩形的尺寸。

题目链接:http://poj.org/problem?id=2185

题目:

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 
 

题目大意:

给出一个矩阵,求最小的可以通过复制包含原矩阵的矩阵大小

题解:

对每一行分别求最小循环节,答案矩阵的宽度就是这些最小循环节的lcm

同理列也是这样处理

 
 
#include<algorithm>
#include<cstring>
#include<iostream>
#include<cstdio>
using namespace std;

const int N=1e4+15;
int r,c,n,m;
int next[N];
char buf[N][80],tmp[N];
int kmp(int l)
{
    next[1]=0;
    for (int i=2,j=0;i<=l;i++)
    {
        while (j&&tmp[i]!=tmp[j+1]) j=next[j];
        if (tmp[i]==tmp[j+1]) j++;
        next[i]=j; 
    }
    return l-next[l];
}
int gcd(int x,int y)
{
    if (!y) return x;
    return gcd(y,x%y);
}
int lcm(int x,int y)
{
    return x/gcd(x,y)*y;
}
int main()
{
    scanf("%d%d",&r,&c);
    for (int i=1;i<=r;i++)
    {
        scanf("%s",buf[i]+1);
    }
    int n=1,m=1;
    for (int i=1;i<=r;i++)
    {
        for (int j=1;j<=c;j++) tmp[j]=buf[i][j];
        n=lcm(n,kmp(c));
        if (n>c)
        {
            n=c;
            break;        
        }
    }
    for (int i=1;i<=c;i++)
    {
        for (int j=1;j<=r;j++) tmp[j]=buf[j][i];
        m=lcm(m,kmp(r));
        if (m>r)
        {
            m=r;
            break;
        }
    }
    printf("%d\n",n*m);
    return 0;
}

 




转载于:https://www.cnblogs.com/xxzh/p/9709891.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值