您的位置:首页 > 其它

POJ 2406 Power Strings

2017-08-22 10:33 417 查看
Power Strings

Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 50920 Accepted: 21254
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


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

题意:输入字符串,问其中最短循环出现的次数。

解题思路:最短循环节的长度cir其实就是字符串的长度len减去最后一个字符的next值,也就是cir=len-next[len]。如果cir能够被len整除,那么循环节出现的次数就是len/cir。如果不能整除那么说明该循环节是第一次出现。

AC代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAXN = 1e6 + 10; //最大的字符串长度
char str[MAXN];
int fail[MAXN];
void get_fail(int n) //失配数组
{
memset(fail,0,sizeof(fail));
fail[0]=0;
fail[1]=0;
for(int i=1;i<n;i++)
{
int j=fail[i];
while(j && str[i]!=str[j]) j=fail[j];
fail[i+1]=str[i]==str[j]?j+1:0;
}
}
void solve()
{
int len=strlen(str); //字符串的长度
get_fail(len); //得到失陪数组
int cir=len-fail[len]; //最短的循环节长度
if(len%cir!=0) printf("1\n"); //第一次出现
else printf("%d\n",len/cir); //出现次数
}
int main(void)
{
while(gets(str)) //输入字符串
{
if(str[0]=='.') break; //不满足要求,退出循环
solve(); //处理函数
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: