• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
LyonLys
愿意在角落唱沙哑的歌 再大声也都是给你 请用心听 不要说话 Contact me via E-mail: lyon.lys@gmail.com
博客园    首页    新随笔    联系   管理    订阅  订阅

hdu 1358 Period (KMP求循环次数)

Problem - 1358

  KMP求循环节次数。题意是,给出一个长度为n的字符串,要求求出循环节数大于1的所有前缀。可以直接用KMP的方法判断是否有完整的k个循环节,同时计算出当前前缀的循环节的个数。

代码如下:

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <iostream>
 4 #include <algorithm>
 5 
 6 using namespace std;
 7 
 8 const int N = 1111111;
 9 char buf[N];
10 int next[N];
11 
12 void getNext(char *str, int len) {
13     int i = 0, j = -1;
14     next[0] = -1;
15     while (i <= len) {
16         while (j > -1 && str[i] != str[j]) j = next[j];
17         i++, j++;
18         next[i] = j;
19     }
20 }
21 
22 typedef pair<int, int> PII;
23 PII rec[N];
24 
25 int main() {
26     int n, cas = 1;
27     while (cin >> n && n) {
28         cin >> buf;
29         getNext(buf, n);
30 //        for (int i = 0; i <= n; i++) cout << next[i] << ' '; cout << endl;
31         int cnt = 0;
32         for (int i = 1; i <= n; i++) {
33             if (i % (i - next[i])) continue;
34             if (i / (i - next[i]) == 1) continue;
35             rec[cnt++] = PII(i, i / (i - next[i]));
36         }
37         sort(rec, rec + cnt);
38         printf("Test case #%d\n", cas++);
39         for (int i = 0; i < cnt; i++) {
40             printf("%d %d\n", rec[i].first, rec[i].second);
41         }
42         puts("");
43     }
44     return 0;
45 }
View Code

 

——written by Lyon

posted @ 2013-06-28 03:26  LyonLys  阅读(223)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3