poj 2406 Power Strings(kmp)

本文介绍了一种算法,用于解决字符串幂运算的问题。通过识别字符串的循环节,算法可以找出使字符串s等于某个字符串a的幂的最大次数n。文章提供了详细的代码实现,包括如何获取循环节和判断是否满足条件。

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

题意:给你定义字符串的幂 然后给你一个串s 问 幂次最大为多少

思路:找到字符串的循环节 然后看下有没有满足的循环节 没有就输出1

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
#define ll long long int
using namespace std;
inline ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
inline ll lcm(ll a,ll b){return a/gcd(a,b)*b;}
int moth[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int dir[4][2]={1,0 ,0,1 ,-1,0 ,0,-1};
int dirs[8][2]={1,0 ,0,1 ,-1,0 ,0,-1, -1,-1 ,-1,1 ,1,-1 ,1,1};
const int inf=0x3f3f3f3f;
const ll mod=1e9+7;
char s[1000007];
int nextt[1000007];
void getnext(){
    nextt[1]=0;
    int len=strlen(s);
    for(int i=2,j=0;i<=len;i++){
        while(j>0&&s[i-1]!=s[j]) j=nextt[j];
        if(s[i-1]==s[j]) j++;
        nextt[i]=j;
    }
}
int main(){
    //ios::sync_with_stdio(false);
    while(~scanf("%s",s)){
        if(strlen(s)==1&&s[0]=='.') break;
        getnext();
        int len=strlen(s);
        int temp=nextt[len];
        while(len%(len-temp)!=0){
            temp=nextt[temp];
            if(len/(len-temp)<2)
            break;
        }
        if(len%(len-temp)==0)
        printf("%d\n",len/(len-temp));
        else printf("1\n");
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/wmj6/p/10496519.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值