POJ 2406 Power Strings hash求匹配

题目:

http://poj.org/problem?id=2406

题意:

给出一个不超过1e6的字符串,求这个字符串最多有多少个周期。

思路:

其实就是求最小周期长度,然后用字符串总长度除以最小周期长度,就是答案。最最正宗的写法应该是kmp吧,这里用了hash算法,可以求出任意一段区间的hash值,枚举最小周期长度,然后用hash值判断之后的每个等长度区间是否一样

#include 
#include 
#include 
#include 
using namespace std;

typedef unsigned long long ull;
const int N = 1000000 + 10;
const int seed = 131;
char ori[N];
ull Seed[N], hash_ori[N];
int main()
{
    Seed[0] = 1;
    for(int i = 1; i < N; i++) Seed[i] = Seed[i-1] * seed;
    while(scanf("%s", ori + 1))
    {
        int len = strlen(ori+1);
        if(len == 1 && ori[1] == '.') break;
        hash_ori[0] = 0;
        for(int i = 1; i <= len; i++)//BKDRhash算法
            hash_ori[i] = hash_ori[i-1] * seed + ori[i];
        int ans = 0;
        for(int i = 1; i <= len; i++)
        {
            if(len % i) continue;
            bool f = true;
            ull tmp = hash_ori[i] - hash_ori[0] * Seed[i];//枚举区间的hash值
            for(int j = i; j <= len; j += i)
            {//hash_ori[j] - hash_ori[j-i] * Seed[i]就是区间[i+1,j]的hash值
                if(hash_ori[j] - hash_ori[j-i] * Seed[i] != tmp)
                {
                    f = false; break;
                }
            }
            if(f)
            {
                ans = i; break;
            }
        }
        printf("%d\n", len / ans);
    }
    return 0;
}

你可能感兴趣的:(hash)