poj 2406 Power Strings (字符串哈希初见)

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long LL;
char s[1001000];
int mod = 10009;   // 模
int len, k = 131;  // s的长度为 len
LL hash[1001000];  // hash[i]存储以第 i 个字符为尾的前缀的散列值
LL cal(LL x, LL y) // 计算和返回 y^x % mod 的结果值
{
    LL ans = 1; // 结果值初始化
    while (x)   // 分析次幂 x 的每一个二进制位
    {
        if (x & 1)
            ans = (ans * y) % mod; // 若当前位为 1,则累乘当前位的权并取模
        x >>= 1;
        y = (y * y) % mod; // 次幂 x 右移一位,计算该位的权后取模
    }
    return ans; 
}
bool check(int x) // 若所有长度为 x 的相邻子串对应的散列函数值相等,;则返回 true;否则返回 false
{
    LL cc = cal(LL(x), (LL)k);               // 计算 k^x % mod;
    for (int i = (x << 1); i <= len; i += x) 
    {
        if ((hash[i] - (hash[i - x] * cc) % mod + mod) % mod != hash[x])
        {
            return false;
        }
    }
    return true;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
#endif
    while (1)
    {
        scanf("%s", s + 1);          // 输入字串
        len = strlen(s + 1);         // 计算字串长度
        if (len == 1 && s[1] == '.') // 返回空串的次幂 0
        {
            return 0;
        }
        for (int i = 1; i <= len; i++) // 计算所有前缀的散列值
        {
            hash[i] = (hash[i - 1] * k + s[i]) % mod;
        }
        for (int i = 1; i <= len; i++) // 枚举可能的子串长度
        {
            if (len % i == 0 && check(i)) // 若 s 能够划分出长度 i 的子串且所有相邻子串的散列值相等,则输出子串个数,并退出 for 循环
            {
                printf("%d\n", len / i);
                break;
            }
        }
    }
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值