HRBEU 字符串 1003

http://acm.hrbeu.edu.cn/index.php?act=problem&id=1003&cid=20 

题目的意思:给你一段字符串,让你输出这段字符串是由某个它的子串最大的重复次数n满足str=sbr^n,sbr为子串。

解题思路:首先由KMP算出所给的这段字符串的K值,然后再由2*next[len(strlen(str))]和len的关系来确定

n的值

(1),若前者小于后者,则最小重复串的长度为len,即n=1;

(2),若前者大于等于后者 1),如果len%(len-next[len])==0 则最小的重复串为len-next[len],即重复次数n=len/(len-next[len])。2),若了len%(len-next[len])!=0 ,则最小重复串长度为len,次数n=1;

#include<stdio.h>
#include<string.h>
#include<iostream>
using namespace std;
#define N 1000000
int next[N];
char s[N];
void get_next(int n)
{
    int i=0,j=-1;
    next[0]=-1;
    while(i<=n)
    {
        if(j==-1||s[i]==s[j])
        {
            i++;
            j++;
            next[i]=j;
        }
        else j=next[j];
    }
}
int main()
{
    while(scanf("%s",s)!=EOF)
    {
        if(s[0]=='.') break;
        int len=strlen(s);
        get_next(len);
        ////for(int i=0;i<=len;i++)
        //cout<<next[i]<<" ";
        //cout<<endl;
        if(2*next[len]<len)
        {
            cout<<"1\n";
        }
        else
        {
            int m=len%(len-next[len]);
            if(!m)
            {cout<<len/(len-next[len])<<endl;}
            else
            {cout<<"1\n";}
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/fxh19911107/p/2271865.html