HDU 1358 Period(KMP算法应用)

来源:互联网 发布:java代码运行流程图 编辑:程序博客网 时间:2024/05/20 17:07

For each prefix of a given string S with N characters (each character has an ASCII code between 97 and 126, inclusive), we want to know whether the prefix is a periodic string. That is, for each i (2 <= i <= N) we want to know the largest K > 1 (if there is one) such that the prefix of S with length i can be written as A K , that is A concatenated K times, for some string A. Of course, we also want to know the period K. 
Input
The input file consists of several test cases. Each test case consists of two lines. The first one contains N (2 <= N <= 1 000 000) – the size of the string S. The second line contains the string S. The input file ends with a line, having the number zero on it. 
Output
For each test case, output “Test case #” and the consecutive test case number on a single line; then, for each prefix with length i that has a period K > 1, output the prefix size i and the period K separated by a single space; the prefix sizes must be in increasing order. Print a blank line after each test case. 
Sample Input
3aaa12aabaabaabaab0
Sample Output
Test case #12 23 3Test case #22 26 29 312 4

【题解】 

 KMP算法应用题,题意是从序列首开始遍历,寻找相同子序列数大于等于2的序列终点位置和相同子序列的个数,比如样例1就是i=2时有两个相同的子序列a,a,序列i=3时有三个想通过的子序列a,a,a。

直接套用KMP模板,中间判断一下,如果符合条件就输出。


ps:这道题我实在virtual judge 上交的,ce了好几次,这个平台上不支持数组名与关键字相同,就是说,在代码中用next做数组名在电脑上可以运行,但是交上去会ce,所以稍微改一下数组名就好了。

【AC代码】

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>using namespace std;const int N=1e6+10;int next_t[N];string s;int m,n;void get_next(){    int k=-1,i=0;    next_t[0]=-1;    while(i<s.size())    {        if(k==-1 || s[i] == s[k])        {            k++;            i++;            if(i%(i-k)==0 && i/(i-k)>1)            {                printf("%d %d\n",i,i/(i-k));            }            next_t[i]=k;        }        else            k=next_t[k];    }}int main(){    int cnt=1;    while(~scanf("%d",&m),m)    {        cin>>s;        printf("Test case #%d\n",cnt++);        get_next();        cout<<endl;    }    return 0;}


原创粉丝点击