POJ2406 Power Strings

来源:互联网 发布:算法设计与分析分治法 编辑:程序博客网 时间:2024/06/15 18:31

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.

POJ怎么大多都是英文题…
继续翻译…
如下:
给定一个字符串L,已知这个字符串是由某个字符串S重复R次而得到的,求R的最大值。

表面上看是后缀数组,事实上是一道暴力!
暴力做法如下:枚举每一串,是否匹配,如果是字符串字母数的整倍数就是答案

#include<cstdio>#include<cstring>#include<algorithm>using namespace std;int a[1100000],n=0;int main(){    while(1)    {        char st[1100000];        scanf("%s",st+1);int len=strlen(st+1);        if(st[1]=='.'&&len==1)break;        int i=2,j=1;        while(i<=len)        {            if(st[i]==st[j])            {                i=i+1;                j=j+1;            }            else            {                j=1;                i++;            }        }        if(len%(i-j)==0)printf("%d\n",len/(i-j));        else printf("1\n");    }    return 0;}

后缀数组也算简单,如下:
穷举字符串S的长度k,然后判断是否满足。判断的时候,先看字符串L的长度能否被k整除,再看suffix(1)和suffix(k+1)的最长公共前缀是否等于n-k。在询问最长公共前缀的时候,suffix(1)是固定的,所以RMQ问题没有必要做所有的预处理,只需求出height数组中的每一个数到height[rank[1]]之间的最小值即可。整个做法的时间复杂度为O(n)。

代码本人没有打……

by_lmy

0 0