Olympiad in Informatics

POJ2185: Milking Grid — Solution

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:

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.

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.

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.