HUST 1010 The Minimum Length (裸KMP)【KMP模板】

来源:互联网 发布:cf手游一键领取软件 编辑:程序博客网 时间:2024/06/05 02:03

There is a string A. The length of A is less than 1,000,000. I rewrite it again and again. Then I got a new string: AAAAAA...... Now I cut it from two different position and get a new string B. Then, give you the string B, can you tell me the length of the shortest possible string A. For example, A="abcdefg". I got abcdefgabcdefgabcdefgabcdefg.... Then I cut the red part: efgabcdefgabcde as string B. From B, you should find out the shortest A.
Input
Multiply Test Cases. For each line there is a string B which contains only lowercase and uppercase charactors. The length of B is no more than 1,000,000.
Output
For each line, output an integer, as described above.
Sample Input
bcabcabefgabcdefgabcde
Sample Output
37

 【题解】 这就是道裸的KMP题,相当于模板。

 【AC代码】

#include<cstdio>#include<algorithm>#include<cstring>using namespace std;int nex[1000005];char s[1000005];void getnext(int n)//模板{    int i=0,j=-1;    nex[0]=-1;    while(i<n)    {        if(j == -1||s[i] == s[j])        {            i++;            j++;            nex[i]=j;        }        else            j=nex[j];    }}int main(){    while(~scanf("%s",s))    {        memset(nex,0,sizeof(nex));        int len=strlen(s);        getnext(len);        int ans=len-nex[len];        printf("%d\n",ans);    }    return 0;}


原创粉丝点击