【KMP思想求循环节】hdu 1358 hust 1010 poj 2406

来源:互联网 发布:手机连不上虚拟网络 编辑:程序博客网 时间:2024/06/05 00:41

字符串的循环节为  字符串长度减去字符串最长公共前后缀的长度。

hdu 1358

#include<iostream>#include<cstdio>#include<cstring>#include<cmath>#include<stack>#include<queue>#include<deque>#include<map>#include<algorithm>using namespace std;typedef long long LL;//#pragma comment(linker, "/STACK:102400000,102400000")/*HDU - 3746给出一个字符串,问还需要在后面添加多少个字符才能使它变成由一个前缀循环多次而成无非求一个next[n]*/const double PI = acos(-1.0);const double eps = 1e-6;const int INF=0x3f3f3f3f;const int mod = 1e9;const int N = 100010;char s[N];int nex[N];void getnext(char *p){    int len = strlen(p);    int k = -1;    nex[0] = k;    for(int i = 1; i < len; i++)    {        while(k!=-1 && p[i]!=p[k+1])            k = nex[k];        if(p[i]==p[k+1])            k++;        nex[i] = k;    }}int main(){    int T;    scanf("%d",&T);    while(T--)    {        scanf("%s",s);        getnext(s);        int len = strlen(s);        int x = nex[len-1]+1;        x = len-x;        if(x == len)        {            printf("%d\n",x);            continue;        }        if(len%x == 0)            puts("0");        else            printf("%d\n",x-len%x);    }    return 0;}

其他两题没什么变化。

原创粉丝点击