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

[POJ2406]Power Strings

时间:2015-08-26 21:54:33      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

题目链接:http://poj.org/problem?id=2406

 

Description

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).

Input

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.

Output

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

Sample Input

abcd
aaaa
ababab
.

Sample Output

1
4
3

Hint

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

Source

 
 
给你一个字串,这个串是里面的某子串循环n次得到的,求这个n。
KMP求循环节,两个公式:如果n % (n - pre[n]) == 0说明存在循环节,循环次数为n / (n - pre[n])
 
 
 
 1 #include <cstdio>
 2 #include <cstdlib>
 3 #include <cstring>
 4 #include <algorithm>
 5 #include <iostream>
 6 #include <cmath>
 7 #include <queue>
 8 #include <map>
 9 #include <stack>
10 #include <list>
11 #include <vector>
12 
13 using namespace std;
14 
15 const int maxn = 66666666;
16 int na, nb;
17 char a[maxn];
18 char b[maxn];
19 int pre[maxn];
20 
21 //b是模式串,a是目标串
22 void getpre(char *b, int *pre) {
23     int j, k;
24     pre[0] = -1;
25     j = 0;
26     k = -1;
27     while(j < nb) {
28         if(k == -1 || b[j] == b[k]) {
29             j++;
30             k++;
31             pre[j] = k;
32         }
33         else {
34             k = pre[k];
35         }
36     }
37 }
38 
39 int kmp() {
40     int ans = 0;
41     int i = 0;
42     int j = 0;
43     getpre(b, pre);
44     while(i < na) {
45         if(j == -1 || a[i] == b[j]) {
46             i++;
47             j++;
48         }
49         else {
50             j = pre[j];
51         }
52         if(j == nb) {
53             ans++;
54         }
55     }
56     return ans;
57 }
58 
59 int main() {
60     freopen("in", "r", stdin);
61     while(~scanf("%s", b) && strcmp(".", b)) {
62         nb = strlen(b);
63         getpre(b, pre);
64         int loop = nb - pre[nb];
65         if(nb % loop == 0) {
66             printf("%d\n", nb / loop);
67         }
68         else {
69             printf("1\n");
70         }
71     }
72 }

 

[POJ2406]Power Strings

标签:

原文地址:http://www.cnblogs.com/vincentX/p/4761550.html

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