Oulipo 【HDU - 1686】【哈希 | KMP】

题目链接

求模式串在待匹配串的出现次数。

Input

第一行是一个数字T,表明测试数据组数。
之后每组数据都有两行:第一行为模式串,长度不大于10000;第二行为待匹配串,长度不大于1000000。所有字符串只由大写字母组成。

Output

每组数据输出一行结果。

 

直接上哈希就是了——当然,这里用到的是KMP优化过后的哈希处理。

细节是,不要用取mod,直接用无符号类型,不然会被卡。

完整代码:

#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 lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
using namespace std;
typedef unsigned long long ull;
typedef long long ll;
const ull hash1=131, hash2=233;
const int maxN=1e6+5;
char a[maxN], b[maxN];
ull a_hash1, b_hash1, ba1, a_hash2, b_hash2, ba2;
int main()
{
    int T;  scanf("%d", &T);
    while(T--)
    {
        getchar();
        scanf("%s", a);
        getchar();
        scanf("%s", b);
        int lena=(int)strlen(a), lenb=(int)strlen(b);
        a_hash1=b_hash1=a_hash2=b_hash2=0;
        ba1=ba2=1;
        for(int i=0; i<lena; i++)
        {
            a_hash1 = (a_hash1*hash1 + a[i]);
            a_hash2 = (a_hash2*hash2 + a[i]);
            b_hash1 = (b_hash1*hash1 + b[i]);
            b_hash2 = (b_hash2*hash2 + b[i]);
            ba1 = ba1*hash1;
            ba2 = ba2*hash2;
        }
        int ans=( ( a_hash1==b_hash1 && a_hash2==b_hash2 )?1:0 );
        for(int i=0; i+lena<lenb; i++)
        {
            b_hash1 = (b_hash1*hash1 + b[i+lena] - b[i]*ba1 );
            b_hash2 = (b_hash2*hash2 + b[i+lena] - b[i]*ba2 );
            if(b_hash1==a_hash1 && a_hash2==b_hash2) ans++;
        }
        printf("%d\n", ans);
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wuliwuliii

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值