您的位置:首页 > 其它

HUST 1010(KMP应用:最短循环节点)

2016-02-17 17:16 549 查看
F - The Minimum Length
Time Limit:1000MS     Memory Limit:131072KB     64bit IO Format:%lld
& %llu
Submit Status

Description

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 abcd efgabcdefgabcdefgabcdefg.... 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

bcabcab
efgabcdefgabcde


Sample Output

3
7


题意:有一个字符串S,它是由重复的一个子串组成的,例如:ABABABAB,那么这个子串就是:AB,现在给出串的一部分给你,例如:BAB。让你求这个子串

题解:错了很多次,诶,看了题解是:根据KMP的原理,是将前缀与后缀的最大匹配那么最后的fail
的值就是除了第一个子串剩下的长度,那么直接使用n-fail
就可以了,自己画了一些字符串,匹配了一下,这个结论确实是对的,还是需要理解理解吗,算是KMP的一种题型吧:最短循环节点

我们其实可以看一个例子:比如AAAAAAAAA

他的fail指针就是----------->>>>>0123456789

字符串每一次最大的匹配前缀,与后缀的长度,那么显然每匹配一次就在原来的基础长度上+1。

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
#define N  1000000+5
char s
;
int fail
;
int ans;
void getfail(char *p,int *f)
{
int m=strlen(p);
f[0]=0;f[1]=0;
for(int i=1;i<m;i++)
{
int j=f[i];
while(j&&p[i]!=p[j])j=f[j];
f[i+1]=p[i]==p[j]?j+1:0;
}
}
int main()
{
#ifdef CDZSC
freopen("i.txt","r",stdin);
#endif
while(~scanf("%s",s))
{
ans=1;
getfail(s,fail);
int len=strlen(s);
printf("%d\n",len-fail[len]);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: