---
id: 313
lang: en
translation_of: index.md
source_sha256: 22496f24ffbd6aa29163694cfb35ee985aaaa916485bb1925fcfe8c506fd9a12
title: "POJ2185: Milking Grid — Solution"
description: "Finding the smallest tile of a grid: naive matching gives the column period, and KMP's next array over whole rows gives the row period."
tags: ["OI","KMP"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes: []
---

## A Clever Use of the next Array

The problem asks for the smallest submatrix that can tile the original matrix. We can solve this with the KMP approach. First we need to find the horizontal length of the periodic matrix, which we can handle with naive matching:

<!--more-->

```cpp
for (int i = 1; i <= R; i++)
{
    scanf("%s", src[i] + 1);
    strcpy(tmp + 1, src[i] + 1);
    for (int len = C; len > 1; len--)
    {
        tmp[len] = 0;
        int x, y;
        for (x = 1, y = 1; y <= C; x++, y++)
        {
            if (!tmp[x])
                x = 1;
            if (src[i][y] != tmp[x])
                break;
        }
        if (y == C + 1)
            seg[len]++;
    }
}
```

Here $src[][]$ is the original matrix. In each row we enumerate $len$ as the period length; we can find the period by naive matching, and record how many times that period repeats. Only the shortest period with a repeat count of $R$ can serve as part of the solution.

Then we quickly scan for the shortest valid period, and set the period position to 0 to make the later matching convenient.

```cpp
int width = C + 1;
for (int i = 1; i <= C; i++)
    if (seg[i] == R)
    {
        width = i;
        break;
    }
for (int i = 1; i <= R; i++)
    src[i][width] = 0;
```

Next we find the minimum period length between rows. We can compare the rows one by one, filling in the next array. After that, we get our minimum period length.

```cpp
for (int i = 2, k = 0; i <= R; i++)
    {
        while (k && strcmp(src[i] + 1, src[k + 1] + 1))
            k = nxt[k];
        if (!strcmp(src[i] + 1, src[k + 1] + 1))
            k++;
        nxt[i] = k;
    }
```

Finally, just multiply and output.
