Oulipo-HDU-1686 哈希

这个题我之前用kmp板子写过一次,这次开始学习哈希,再上一个单哈希的方法,就当入门模板吧。
###思路:
算出子字符串的哈希值,然后遍历主字符串枚举起点,算出和相同长度子串的哈希值,如果值相同则答案加1。
代码如下:

#include<iostream>
#include<cstdio>
#include<fstream>
#include<set>
#include<cmath>
#include<cstring>
#include<string>
#include<map>
#include<vector>
#include<iomanip>
#include<cstdlib>
#include<list>
#include<queue>
#include<stack>
#include<algorithm>
#define inf 0x3f3f3f3f
#define MOD 1000000007
#define mem0(a) memset(a,0,sizeof(a))
#define mem1(a) memset(a,-1,sizeof(a))
#define meminf(a) memset(a,inf,sizeof(a))
#define HASHP 13331;//加了一个哈希公式中的p,据说13331很玄学?反正作为萌新先用着看看
typedef long long ll;
typedef unsigned long long ull;
using namespace std;
char w[10010],T[1000100];
ull hash1[10010],hash2[1000100],xp[10010];
void init()
{
  xp[0]=1;
  for(int i=1;i<=10000;i++)xp[i]=xp[i-1]*13331;
}
int make_hash(char *s,ull *hash)//逆序构造单哈希数组
{
  int len=strlen(s);
  hash[len]=0;
  for(int i=len-1;i>=0;i--)hash[i]=hash[i+1]*13331+s[i]-'A'+1;
  return len;
}
int get_hash(char *s,ull *hash,int qi,int l)//计算子字符串哈希值
{
  return hash[qi]-hash[qi+l]*xp[l];
}
int main()
{
  std::ios::sync_with_stdio(false);
  cin.tie(0);
/*  freopen("test.txt","r",stdin);
  freopen("output.txt","w",stdout);*/
  int t;
  cin>>t;
  init();//初始化Xp数组
  while(t--)
  {
    cin>>w>>T;
    //主要是为了初始化出两个字符串的前缀哈希数组
    int lenw=make_hash(w,hash1);
    int lent=make_hash(T,hash2);
    ull hashw=hash1[0];//目标子串的哈希值
    int count=0;//答案
    for(int i=0;i<=lent-lenw;i++)//枚举子字符串起点
    {
      ull hasht=get_hash(T,hash2,i,lenw);//算出子串哈希值
      if(hasht==hashw)count++;
    }
    cout<<count<<endl;
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值