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 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?