hdu 1358(Period)next数组的运用 计算前i个字符的循环周期 /poj 2406 计算字符串的周期...

刚开始,以为统计整个字符串的有多少个循环然后输出,结果一直是output limit excesded;

原来是让计算前i个字符的循环;

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 using namespace std;
 5 #define N 1000006
 6 char str[N];
 7 int next[N];
 8 int n;
 9 void get_next()
10 {
11 
12     int i=0,j=-1;
13     next[0]=-1;
14     while(i<n)
15     {
16 
17         if(j==-1||str[i]==str[j])
18         {
19 
20             i++;
21             j++;
22             next[i]=j;
23 
24         }
25         else{
26             j=next[j];
27         }
28     }
29 }
30 int main()
31 {
32     int flag=1;
33     while(scanf("%d",&n)!=EOF)
34     {
35         if(n==0)  break;
36         getchar();
37         scanf("%s",str);
38         memset(next,0,sizeof(next));
39         get_next();
40         //int t=n-next[n];
41         printf("Test case #%d\n",flag++);
42         int i;
43         for(i=2;i<=n;i++)
44         {
45             if(i%(i-next[i])==0&&next[i]!=0)
46             {
47 
48                 printf("%d %d\n",i,i/(i-next[i]));
49             }
50         }
51         printf("\n");
52     }
53     return 0;
54 
55 
56 
57 }

 虽然题目每太读懂,但是正是在练习KMP,看了测试实例,就了解了。

单纯的求循环周期。

 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 using namespace std;
 5 #define N 1000006
 6 char str[N];
 7 int next[N];
 8 void get_next()
 9 {
10 
11     int i=0,j=-1;
12     next[0]=-1;
13     int len=strlen(str);
14     while(i<len)
15     {
16        if(j==-1||str[i]==str[j])
17        {
18            i++;
19            j++;
20            next[i]=j;
21        }
22        else
23         j=next[j];
24     }
25   //  for(i=1;i<=len;i++)
26  //   printf("%d ",next[i]);
27  //   printf("\n");
28 
29 
30 
31 }
32 int  main()
33 {
34     while(scanf("%s",str)!=EOF)
35     {
36         if(str[0]=='.') break;
37         memset(next,0,sizeof(next));
38         get_next();
39         int len=strlen(str);
40         int t=len-next[len];
41         if(t<=next[len]&&next[len]%t==0)
42         {
43             printf("%d\n",next[len]/t+1);
44         }
45         else
46             printf("1\n");
47 
48 
49     }
50     return 0;
51 }

 

 

 

 

 

转载于:https://www.cnblogs.com/heat-man/archive/2013/04/30/3052287.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值