HDU 4763 – Theme Section [KMP应用]




It’s time for music! A lot of popular musicians are invited to join us in the music festival. Each of them will play one of their representative songs. To make the programs more interesting and challenging, the hosts are going to add some constraints to the rhythm of the songs, i.e., each song is required to have a ‘theme section’. The theme section shall be played at the beginning, the middle, and the end of each song. More specifically, given a theme section E, the song will be in the format of ‘EAEBE’, where section A and section B could have arbitrary number of notes. Note that there are 26 types of notes, denoted by lower case letters ‘a’ – ‘z’.

To get well prepared for the festival, the hosts want to know the maximum possible length of the theme section of each song. Can you help us?






#include <bits/stdc++.h>
using namespace std;

const int maxn = 1024000;
int fail[maxn], ok[maxn];
char str[maxn];

void getFail(const char *P, int *f, int len) {
    f[0] = f[1] = 0;
    for(int i = 1; i < len; ++i) {
        int j = f[i];
        while(j && P[i] != P[j]) j = f[j];
        f[i+1] = P[i]==P[j] ? j+1 : 0;

int main() {
    int T; scanf("%d", &T);
    while(T--) {
        scanf("%s", str);
        int len = strlen(str);
        getFail(str, fail, len);
        memset(ok, false, sizeof(ok));
        int f = fail[len];
        while(f) {
            ok[f] = true;
            f = fail[f];
        int ans = 0;
        for(int i = len-1; i >= 0; --i) {
            int cur = fail[i];
            while(cur) {
                if(ok[cur] && i <= len - cur && i >= 2 * cur)
                    ans = max(ans, cur);
                cur = fail[cur];
        printf("%d\n", ans);
    return 0;