首页 > 代码库 > HDU - 4763 Theme Section(kmp)

HDU - 4763 Theme Section(kmp)

题意:字符串E是字符串S的前缀和后缀,同时也出现在字符串S的中间,不与前缀后缀重合,问字符串S中符合要求的字符串E的最大长度。

分析:

1、nex数组的含义,就是从开始截止到当前字符形成的字符串中,前缀与后缀相同的最大长度。

2、所以取len = nex[slen - 1]为枚举字符串E的最大长度,再依次按len = nex[len - 1]枚举。

3、检查字符串E是否在字符串S的中间的方法:检查中间区域的nex值,若nex[id] >= len说明该前缀也出现在中间区域。

nex[id] == len:E是从0到id的字符串的后缀

nex[id] > len:E是从0到id的字符串的后缀中的前一部分。

#include<cstdio>#include<cstring>#include<cstdlib>#include<cctype>#include<cmath>#include<iostream>#include<sstream>#include<iterator>#include<algorithm>#include<string>#include<vector>#include<set>#include<map>#include<stack>#include<deque>#include<queue>#include<list>#define lowbit(x) (x & (-x))const double eps = 1e-8;inline int dcmp(double a, double b){    if(fabs(a - b) < eps) return 0;    return a > b ? 1 : -1;}typedef long long LL;typedef unsigned long long ULL;const int INT_INF = 0x3f3f3f3f;const int INT_M_INF = 0x7f7f7f7f;const LL LL_INF = 0x3f3f3f3f3f3f3f3f;const LL LL_M_INF = 0x7f7f7f7f7f7f7f7f;const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};const int MOD = 1e9 + 7;const double pi = acos(-1.0);const int MAXN = 1e6 + 10;const int MAXT = 10000 + 10;using namespace std;char s[MAXN];int nex[MAXN], slen;void getNext(){    memset(nex, 0, sizeof nex);    for(int i = 1, k = 0; i < slen; ++i){        while(k > 0 && s[i] != s[k]){            k = nex[k - 1];        }        if(s[i] == s[k]) ++k;        nex[i] = k;    }}int main(){    int T;    scanf("%d", &T);    while(T--){        scanf("%s", s);        slen = strlen(s);        getNext();        int len = nex[slen - 1];        int ans = 0;        bool ok = false;        while(len > 0 && !ok){            int id = slen - 1 - len;            while(nex[id] == 0 && id >= 2 * len - 1){                --id;            }            while(id >= 2 * len - 1){                if(nex[id] >= len){                    ok = true;                    ans = len;                    break;                }                else --id;            }            len = nex[len - 1];        }        printf("%d\n", ans);    }    return 0;}

  

HDU - 4763 Theme Section(kmp)