---
id: 268
lang: en
translation_of: index.md
source_sha256: 8d0e40bc44affa96549959e728e55162c960333bf39f8cfb96db191aabf3bb83
title: "POJ1961: Period — Solution"
description: "Using the KMP next array to find, for each periodic prefix of a string, its smallest period length and largest frequency."
tags: ["OI","KMP"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "如果区间长度是next[i]的倍数 is translated literally (a multiple of next[i]), even though the code actually tests divisibility by i - next[i] + 1; the author's reasoning is left as written."
---

## Main Idea

This problem asks us to find, for a periodic prefix, the smallest period length and the largest frequency. We can solve it with KMP's next array. Let's first review what the next array means. $next[i]$ is the longest common part of a prefix and a suffix within the range $str[1,i]$. If the length of the range is a multiple of $next[i]$, then it contains a repeating unit. See the code for details.

<!--more-->

## Code

```cpp
// POJ1961.cpp
#include <iostream>
#include <cstdio>

using namespace std;
const int maxn = 1000000 + 1000;
int next[maxn];
string str;

int main()
{
    int siz = 0, cnt = 1;
    while (scanf("%d", &siz) && siz != 0)
    {
        cin >> str;
        // get the next array;
        next[0] = -1;
        for (int i = 1; i < siz; i++)
        {
            int j = next[i - 1];
            while (j >= 0 && str[i] != str[j + 1])
                j = next[j];
            if (str[i] == str[j + 1])
                next[i] = j + 1;
            else
                next[i] = -1;
        }
        for (int i = 0; i < siz; i++)
            ++next[i];
        // we have got it...;
        printf("Test case #%d\n", cnt++);
        for (int i = 1; i < siz; i++)
            if ((i + 1) % (i - next[i] + 1) == 0 && (i + 1) / (i - next[i] + 1) > 1)
                printf("%d %d\n", i + 1, (i + 1) / (i - next[i] + 1));
        puts("");
    }
    return 0;
}
```
