KMP POJ 2406 Power Strings解题报告

本文介绍了一个基于KMP算法解决字符串幂运算的问题,通过构造next数组判断一个字符串是否能由更短的子串重复构成,提供了完整的C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Power Strings
Time Limit: 3000MS Memory Limit: 65536K
Total Submissions: 40543 Accepted: 16865
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
Waterloo local 2002.07.01

解法:用KMP的next数组。len是字符串长度,如果len-next[len]能够整除len那么len/(len-next[len])就是解。如果len-next[len]==0,表示字符串由单个字符复制而成,答案是1。剩下的情况下答案就是len,只能由字符串本身组成。
证明:首先理解next数组:next[i]=k表示字符串前i个字符最长的相同前缀和后缀(不包括字符串本身)的长度是k。
存在字符串S:
这里写图片描述
如果有next[6]=4。
这里写图片描述
那么:6-4=2,2可以整除6,表示可以由6/2=3个相同的字符串组合得到。因为从图中可以清楚看到:S1s2=s3s4=s5s6!
len-next[len]不能整除len的时候,比如dcdcd,len=5,next[len]=3,就只能由字符串本身组合成。

//5616K 110MS
#include<stdio.h>
#include<stdlib.h> 
#include<algorithm>
#include<iostream>
#include<string.h>
#define MAX 1000005 
using namespace std;
char s[MAX];
int next[MAX],len;
void get_next(){
     next[0]=-1,len=strlen(s);
     int pre=-1,suf=0;
     while(suf!=len){
        if(-1==pre||s[suf]==s[pre])
           next[++suf]=++pre;
        else pre=next[pre];
     }
}
int main(){
    freopen("i.txt","r",stdin);
    while(~scanf("%s",s)&&strcmp(s,".")){ 
        get_next();
        int tmp=len-next[len];
        if(tmp!=0&&len%tmp==0)   
          cout<<len/tmp<<endl;
        else if(tmp==0)  cout<<len<<endl;
        else  cout<<1<<endl;
    }
    return 0;
}

欢迎留言,积极讨论,一起进步!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值