您的位置:首页 > 其它

HDU 3746 Cyclic Nacklace(KMP最小覆盖子串)

2015-07-17 10:56 344 查看
KMP求出f数组后,最小覆盖子串为长度为len-f[len]的前缀。证明在前面的文章里。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

char c[100005];
int T;
int f[100005];
int main(){
    scanf("%d",&T);
    while(T--){
        scanf("%s",c);
        f[0]=f[1]=0;
        int len=strlen(c);
        for(int i=1;i<len;i++){
            int j=f[i];
            while(j&&c[i]!=c[j]) j=f[j];
            f[i+1]=(c[i]==c[j]?j+1:0);
        }
        int cir=len-f[len];
        int res=0;
        if(cir==len) res=len;
        else {
            if(len%cir==0) res=0;
            else res=cir-len%cir;
        }
        printf("%d\n",res);
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: