HDU 4763 – Theme Section [KMP应用]

Link

传送门

Problem

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?

Mean

给你一个字符串,最长为10^6,让你找出一个最长的连续子串,在原串的头部尾部和中间分别出现,并且三部分不能交叉。

Analysis

这道题是对KMP思想的应用。首先求出失配数组,根据这个数组标记出所有首部尾部相同的位置。然后扫描这个字符串,判断是不是中间出现的那部分。

Code

#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;
}

欢迎留言