您的位置:首页 > 其它

POJ -2406 power strings --KMP中next函数的应用

2012-08-13 10:47 381 查看
PowerStrings

TimeLimit:3000MSMemoryLimit:65536K
TotalSubmissions:23370Accepted:9811
Description

Giventwostringsaandbwedefinea*btobetheirconcatenation.Forexample,ifa="abc"andb="def"thena*b="abcdef".Ifwethinkofconcatenationasmultiplication,exponentiationbyanon-negativeintegerisdefinedinthenormalway:a^0=""(theemptystring)anda^(n+1)=a*(a^n).
Input

Eachtestcaseisalineofinputrepresentings,astringofprintablecharacters.Thelengthofswillbeatleast1andwillnotexceed1millioncharacters.Alinecontainingaperiodfollowsthelasttestcase.
Output

Foreachsyoushouldprintthelargestnsuchthats=a^nforsomestringa.
SampleInput

abcd
aaaa
ababab
.

SampleOutput

1
4
3



/*功能FunctionDescription:POJ-2406
开发环境Environment:DEVC++4.9.9.1
技术特点Technique:
版本Version:
作者Author:可笑痴狂
日期Date:20120813
备注Notes:
题意:
找出字符串的最小循环周期从而算出最大循环次数
*/
/*
//代码一:-----简单枚举法
#include<stdio.h>
#include<string.h>
chars[1000005];

intmain()
{
inti,len,k,j,flag;
while(scanf("%s",s+1)&&s[1]!='.')
{
len=strlen(s+1);
//printf("%d\n%c",len,s[1]);
for(i=1;i<=len;++i)
{
if(len%i)
continue;
flag=1;
for(k=1;flag&&k<=i;++k)
{
for(j=2;j<=len/i;++j)
{
if(s[k]!=s[i*(j-1)+k])
{
flag=0;
break;
}
}
}
if(flag)
{
printf("%d\n",len/i);
break;
}
}
}
return0;
}
*/

//代码二:-------KMP算法中next函数的性质
/*
设Len是s的长度
给出结论:
如果len%(len-next[len])==0,则字符串中必存在最小循环节,且循环次数即为len/(len-next[len])

题目大意:给出一个字符串,求出是某个字符串的n次方
解决:KMP找出字符串的循环节
若有字符串ai...a(j+m),若next[len+1]=m(字符串从1开始),意味着从ai...am和aj...a(j+m)相等,
假设中间有相交部分(或者相交部分为0)aj....am,若总长度减去相交部分剩余的部分能被总长度整除,
又因为从ai...am和aj...aj+m相等,所以除去相交部分剩余的的两段字符串相等,而且必定满足中间相交部分也能被起始字符串整除,依照这样,
即可得出最小的循环节

*/

#include<stdio.h>
#include<string.h>
chars[1000005];
intnext[1000005];

voidget_next(intlen)
{
inti,j;
i=0;
j=-1;
next[0]=-1;
while(i<len)
{
if(j==-1||s[i]==s[j])
{
++i;
++j;
next[i]=j;
}
else
j=next[j];
}

/*
while(i<len)//改进算法---改进在某些情况下的缺陷详见数据结构课本P84
{
if(j==-1||s[i]==s[j])
{
++i;
++j;
if(s[i]!=s[j])
next[i]=j;
else
next[i]=next[j];
}
else
j=next[j];
}
*/
}

intmain()
{
inti,len,k,j,flag;
while(scanf("%s",s)&&s[0]!='.')
{
len=strlen(s);
get_next(len);
if(len%(len-next[len])==0)
printf("%d\n",len/(len-next[len]));
else
printf("1\n");
}
return0;
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: