POJ 3461 Oulipo hash求匹配

题目:

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

题意:

给一个模式串,一个原串,问原串中有多少个模式串

思路:

kmp模板题,这里用hash算法

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

typedef long long ll;
typedef unsigned long long ull;
const int N = 1000000 + 10, M = 10000 + 10, INF = 0x3f3f3f3f;
const int seed = 31;//31,131,1313,13131,131313...
char pat[M], ori[N];
ull Seed[N], hash_ori[N];
ull BKDRhash(char *str)
{
    ull h = 0;
    for(int i = 0; str[i]; i++)
        h = h * seed + str[i];
    return h;
}
int main()
{
    Seed[0] = 1;
    for(int i = 1; i < N; i++) Seed[i] = Seed[i-1] * seed;
    int t;
    scanf("%d", &t);
    while(t--)
    {
        scanf("%s%s", pat+1, ori+1);
        ull hash_pat = BKDRhash(pat+1);
        int len_pat = strlen(pat+1);
        hash_ori[0] = 0;
        int ans = 0;
        for(int i = 1; ori[i]; i++)
        {
            hash_ori[i] = hash_ori[i-1] * seed + ori[i];//也是BKDRhash
            int j = i - len_pat + 1;
            if(j >= 1)
            {
                if(hash_ori[i] - hash_ori[j-1]*Seed[len_pat] == hash_pat) ans++;
            }
        }
        printf("%d\n", ans);
    }
    return 0;
}

你可能感兴趣的:(hash)