码迷,mamicode.com
首页 > 其他好文 > 详细

Power Strings POJ - 2406

时间:2015-09-12 13:35:30      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

Power Strings

POJ - 2406
时限: 3000MS   内存: 65536KB   64位IO格式: %I64d & %I64u

 状态

已开启划词翻译

问题描述

Given two strings a and b we define a*b to be their concatenation. For example, if a = "abc" and b = "def" then a*b = "abcdef". If we think of concatenation as multiplication, exponentiation by a non-negative integer is defined in the normal way: a^0 = "" (the empty string) and a^(n+1) = a*(a^n).

输入

Each test case is a line of input representing s, a string of printable characters. The length of s will be at least 1 and will not exceed 1 million characters. A line containing a period follows the last test case.

输出

For each s you should print the largest n such that s = a^n for some string a.

样例输入

abcd
aaaa
ababab
.

样例输出

1
4
3

提示

This problem has huge input, use scanf instead of cin to avoid time limit exceed.

来源

题意:一个字符串可以由其循环节循环n次得到,问n最大可以是多少……
kmp练习。
 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 
 5 using namespace std;
 6 
 7 #define maxn 10000008
 8 
 9 char s[maxn];
10 int next[maxn];
11 
12 void getNext()
13 {
14     int j, k, i;
15     i = strlen(s);
16 
17     j = 0;
18     k = -1;
19     next[0] = -1;
20     while(j < i)
21     {
22         if(k == -1 || s[j] == s[k])
23         {
24             j++;
25             k++;
26             next[j] = k;
27         }
28         else
29             k = next[k];
30     }
31 }
32 
33 int main()
34 {
35     while(1)
36     {
37         scanf("%s", s);
38         if(s[0] == .)
39             break;
40 
41         int q = strlen(s);
42 
43         memset(next, 0, sizeof(next));
44         getNext();
45 
46         int k = next[q];   // k表示s串 q位置的最长的前缀和后缀相等的长度。q-k代表最小循环节的长度
47 
48         if(q % (q - k) == 0)  // 如果q-k>q 的一半即k 小于s串的一半长度,那么这个式子肯定不成立,输出1.如果q-k小于等于q的一半即k 大于s串的一半长度,那么q-k就是最小循环节的长度
49             printf("%d\n", q / (q - k));
50         else
51             printf("1\n");
52     }
53     return 0;
54 }

 

Power Strings POJ - 2406

标签:

原文地址:http://www.cnblogs.com/Tinamei/p/4802846.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!