【哈希】HDU 1686 Oulipo

HDU 1686 Oulipo

  • 题意:问模式串在文本串中出现过几次。
  • 思路:哈希字符串匹配模板

KMP做法


AC CODE

#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define INF 0x3f3f3f3f
#define lowbit(x) x & (-x)
#define MID (r + l) >> 1
#define lsn rt << 1
#define rsn rt << 1 | 1
#define Lson lsn, l, mid
#define Rson rsn, mid + 1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int maxN = 1e6 + 7;
const ull base = 233;
ull Hash[maxN], p[maxN];
void pre()
{
    p[0] = 1;
    for(int i = 1; i <= 1000000; i ++ )
        p[i] = p[i - 1] * base;
}
ull get_hash(int l, int r, ull *g)
{
    return g[r] - g[l - 1] * p[r - l + 1];
}
char tar[maxN], s[maxN];
int main()
{
    pre();
    int TAT; scanf("%d", &TAT);
    while(TAT -- )
    {
        scanf("%s", tar);
        ull tar_hash = 0;
        int len_tar = strlen(tar);
        for(int i = 1; i <= len_tar; i ++ )
            tar_hash = tar_hash * base + tar[i - 1] - 'A' + 1;
        scanf("%s", s);
        int len = strlen(s);
        Hash[0] = 0;
        for(int i = 1; i <= len; i ++ )
            Hash[i] = Hash[i - 1] * base + s[i - 1] - 'A' + 1;
        int ans = 0;
        for(int i = 1; i <= len - len_tar + 1; i ++ )
        {
            if(get_hash(i, i + len_tar - 1, Hash) == tar_hash)
                ans ++;
        }
        printf("%d\n", ans);
    }
    return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值