POJ 2406 Power Strings
Posted 风中的簌雨
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了POJ 2406 Power Strings相关的知识,希望对你有一定的参考价值。
Time Limit: 3000MS | Memory Limit: 65536K | |
Total Submissions: 44595 | Accepted: 18629 |
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
题目大意: 给定一个字符串,问最多是多少个相同子串不重叠连接构成。
解题思路:KMP的next数组应用。这里主要是如何判断是否有这样的子串,和子串的个数。
若为abababa,显然除其本身外,没有子串满足条件。而分析其next数组,next[7] = 5,next[5] = 3,next[3] = 1,
即str[2..7]可由ba子串连接构成,那怎么否定这样的情况呢?很简单,若该子串满足条件,
则len%sublen必为0。sunlen可由上面的分析得到为len-next[len]。
因为子串是首尾相接,len/sublen即为substr的个数。
若L%(L-next[L])==0,n = L/(L-next[L]),else n = 1
对KMP不太熟悉的可以看这里:从头到尾理解KMP算法
AC代码:
1 #include <stdio.h> 2 #include <string.h> 3 char str[1000010]; 4 int next[1000010]; 5 void getnext() //获取next数组 6 { 7 int i = 0,j = -1; 8 next[0] = -1; 9 int len = strlen(str); 10 while (i < len) 11 { 12 if (j == -1 || str[i] == str[j]) 13 { 14 i ++; 15 j ++; 16 next[i] = j; 17 } 18 else 19 j = next[j]; 20 } 21 } 22 int main() 23 { 24 while (~scanf("%s",str)) 25 { 26 if (strcmp(str,".")==0) //如果str数组为“.”则结束 27 break; 28 int len = strlen(str); 29 getnext(); 30 if (len%(len-next[len])==0) 31 printf("%d\\n",len/(len-next[len])); 32 else 33 printf("1\\n"); 34 } 35 return 0; 36 }
以上是关于POJ 2406 Power Strings的主要内容,如果未能解决你的问题,请参考以下文章