POJ 3461 Oulipo hash求匹配

本文介绍了一种使用Hash算法解决字符串匹配问题的方法,并通过一道具体的POJ题目进行实践。利用BKDRhash函数对模式串和目标串进行哈希计算,实现了高效的子串查找。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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

题意:

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

思路:

kmp模板题,这里用hash算法

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值