FZU - 1901 Period II(kmp所有循环节)

本文介绍了一种使用KMP算法寻找字符串中所有可能的循环节长度的方法。通过解析输入字符串并利用KMP算法预处理得到next数组,进而找到所有的周期前缀,并按长度升序输出这些周期。文章提供了一个完整的C++代码实现。

Problem Description

For each prefix with length P of a given string S,if

S[i]=S[i+P] for i in [0..SIZE(S)-p-1],

then the prefix is a “period” of S. We want to all the periodic prefixs.

 Input

Input contains multiple cases.

The first line contains an integer T representing the number of cases. Then following T cases.

Each test case contains a string S (1 <= SIZE(S) <= 1000000),represents the title.S consists of lowercase ,uppercase letter.

 Output

For each test case, first output one line containing "Case #x: y", where x is the case number (starting from 1) and y is the number of periodic prefixs.Then output the lengths of the periodic prefixs in ascending order.

 Sample Input

4
ooo
acmacmacmacmacma
fzufzufzuf
stostootssto

 Sample Output

Case #1: 3
1 2 3
Case #2: 6
3 6 9 12 15 16
Case #3: 4
3 6 9 10
Case #4: 2
9 12
 
题意:求出一个字符串的所有可能循环节的长度
思路:kmp的运用,题目的意思不是很清楚 j=next[j] 就是次大的匹配个数
#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;
int nextt[1000007];
void getnext(string s){
    nextt[1]=0; int len=s.length(); 
    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);
    int t;
    cin>>t;
    int w=0;
    while(t--){
        string s;
        cin>>s;
        getnext(s);
        int len=s.length();
        queue<int> q;
        int j=nextt[len];
        while(j>0){
            q.push(j);
            j=nextt[j];
        }
        q.push(0);
        bool f=1;
        cout<<"Case #"<<++w<<": "<<q.size()<<endl;
        while(!q.empty()){
            int temp=q.front();
            q.pop();
            if(f){
                cout<<len-temp;
                f=0;
            }else{
                cout<<" "<<len-temp;
            }
        }
        cout<<endl;
    } 
    return 0;
}

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值