【HDU 4763】Theme Section(KMP)

来源:互联网 发布:mac听写与语音没有了 编辑:程序博客网 时间:2024/05/29 11:31

这题数据水的一B,直接暴力都可以过。

比赛的时候暴力过的,回头按照正法做了一发。

匹配的时候 失配函数 其实就是前缀 后缀的匹配长度,之后就是乱搞了。

KMP的题可能不会很直接的出,但是KMP的思想经常渗透在很多题目里面,最近需要多练习一下。

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int maxn = 1000005;int _next[maxn],L;char s[maxn];void kmp_init(){    int i,j;    int m = strlen(s);    j = _next[0] = -1;    i = 0;    while(i < m){        while(j != -1 && s[i] != s[j]) j = _next[j];        _next[++i] = ++j;    }}bool kmp_solve(int len){    int i,j,m = L - len;    i = len;    j = 0;    while(i < m){        while(j != -1 && s[j] != s[i]) j = _next[j];        i++; j++;        if(j >= len){            return true;        }    }    return false;}int main(){    int T;    scanf("%d",&T);    while(T--){        scanf("%s",s);        L = strlen(s);        kmp_init();        int i = L - 1;        int ans = 0;        while(_next[i] >= 0){            if(kmp_solve(_next[i] + 1)){                ans = _next[i] + 1;                break;            }            i = _next[i];        }        printf("%d\n",ans);    }    return 0;}

1 0
原创粉丝点击