B -POJ2406 Hash

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

Hint

This problem has huge input, use scanf instead of cin to avoid time limit exceed.


题意:输入若干个字符串,对于每个字符串求最短的循环节,求出他最多由几个相同的连续子串连接而成。


#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<cmath>
#include<stack>
using namespace std;
typedef unsigned long long ull;
const int N = 1000000+10;
const int p = 131;
char str[N];
ull idx[N], hash[N];
int main()
{
    idx[0] = 1;
    //idx用来记录p的n次方;
    for(int i=1; i<N; i++)
    {
        idx[i]=idx[i-1]*p;
    }

    while(scanf("%s", str+1))
    {
        int len = strlen(str+1);
        //结束条件;
        if(len==1&&str[1]=='.')
            break;
        //计算出字符串从第一位开始,每往后增加一位字符,得到的字符的hash值;
        hash[0] = 0;
        for(int i=1; i<=len; i++)
        {
            hash[i] = hash[i-1]*p+str[i];
        }
        int sum = 0;
        for(int i=1; i<=len; i++)
        {
            //如果整个字符串的长度对循环节长度取模不为零,则说明该循环节不符合要求;
            if(len%i)
                continue;

            bool f = true;
            ull tmp = hash[i];//将找到的循环节(长度为i)的hash值赋给tmp;
            for(int j=i; j<=len; j+=i)
            {
                if(hash[j]-hash[j-i]*idx[i]!=tmp)
                //从第i+1位字符开始向下找长度为i的字符串,判断其hash值是否与tmp相等,
                //相等则继续判断下一段长度为i的循环节,否则,该循环节不满足要求,退出j循环,然后进行判断长度i+1的循环节
                {
                    f = false;
                    break;
                }
            }
            //如果f为true,说明该循环节符合要求,将循环节长度赋给sum,最后总的字符串长度/循环节长度,即为所求;
            if(f)
            {
                sum = i;
                break;
            }
        }
        printf("%d\n", len/sum);
    }
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值