CUMTOJ数据结构作业1 problemD

2019-06-14  本文已影响0人  Redcarp

1762 problem 4.5.17 Power Strings C++

题目描述

Given two strings a and b we define ab to be their concatenation. For example, if a = "abc" and b = "def" then ab = "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).

输入

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.

输出

For each s you should print the largest n such that s = a^n for some string a.

样例输入

abcd
aaaa
ababab
.

样例输出

1
4
3

程序如下

#include<iostream>
#include<cstdio> 
#include<cstring> 
using namespace std;
 
char s[1000005];
int ne[1000001];
void GetNext(char *a)
{
    int len=strlen(a);
    int i=0, j=-1;
    ne[0]=-1;
    while(i<len)
    {
        if(j==-1||a[i]==a[j])
        {
            ne[++i]=++j;
        }
        else j=ne[j];
     }
}

int main()
{
     while(cin>>s&&s[0]!='.')
     {
          GetNext(s);
          int L=strlen(s);
          if(L%(L-ne[L])==0)///如果第i-1位为结尾的循环必定有 i%(i-Next[i])==0
               cout<<(L/(L-ne[L]))<<endl;///0~i-1共有i个字符,i/(i-Next[i])就是循环次数
          else
               cout<<"1"<<endl;
     }
     return 0;
}
上一篇下一篇

猜你喜欢

热点阅读