poj2406 Power Strings(KMP)

定理:假设S的长度为n,则S存在循环子串,当且仅当,n可以被n - next[len]整除,最短循环子串为S[n - next[n]]


例子证明:
设S=q1q2q3q4q5q6q7q8,并设next[8] = 6,此时str = S[len - next[n]] = q1q2,由字符串特征向量next的定义可知,q1q2q3q4q5q6 = q3q4q5q6q7q8,即有q1q2=q3q4,q3q4=q5q6,q5q6=q7q8,即q1q2为循环子串,且易知为最短循环子串。由以上过程可知,若n可以被n - next[n]整除,则S存在循环子串,否则不存在。

解法:利用KMP算法,求字符串的特征向量next,若n可以被n - next[n]整除,则最大循环次数n为n/(n - next[n]),否则为1。


/***********************************************
 * Author: fisty
 * Created Time: 2015-08-29 09:55:23
 * File Name   : E.cpp
 *********************************************** */
#include <iostream>
#include <cstring>
#include <deque>
#include <cmath>
#include <queue>
#include <stack>
#include <list>
#include <map>
#include <set>
#include <string>
#include <vector>
#include <cstdio>
#include <bitset>
#include <algorithm>
using namespace std;
#define Debug(x) cout << #x << " " << x <<endl
#define Memset(x, a) memset(x, a, sizeof(x))
const int INF = 0x3f3f3f3f;
typedef long long LL;
typedef pair<int, int> P;
#define FOR(i, a, b) for(int i = a;i < b; i++)
#define lson l, m, k<<1
#define rson m+1, r, k<<1|1
#define MAX_N 1010000   
char s[MAX_N];
int next[MAX_N];   
void solve(int n){
    int i, j;
    j = next[0] = -1;
    i = 0;
    while(i < n){
        while(-1 != j && s[i] != s[j]) j = next[j];

        next[++i] = ++j;
    }
}
int main() {
    //freopen("in.cpp", "r", stdin);
    //cin.tie(0);
    //ios::sync_with_stdio(false);
    while(~scanf("%s", s)){
        if(s[0] == '.') break;
        int n = strlen(s);
        solve(n);
        if(n % (n - next[n]) == 0){
            printf("%d\n", n / (n - next[n]));
        }else{
            printf("1\n");
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值