两种hash方法(双hash…算了吧,除非字符串很短,然后又wa了才用)
方法1:
unsigned long long hash[N];
定义一个unsigned long long类型的变量,它的范围是在[0, 2^64) 内,这就相当于,当数超不过2^64-1后,它会溢出!这就相当于一个数模2^64的过程。
那么hash函数可以理解为:
hash[i]=(hash[i−1]×p+s[i])%(264)
求区间:
hash[L,R]=hash[R]−hash[L−1]∗p(R−L+1)
P取一个大素数,一般习惯取1e9+7或1e9+9
安全指数:三星(所以并不是很安全)
也就是此份模板(这题也就是用这个):
大致满足字符串>1e4/1e5,因为相对于方法2,这个时间小。
const int Maxn = 1e4 + 10;
const ULL p = 31;
char s1[Maxn], s2[Maxn*100];
ULL has[Maxn*100], f[Maxn*100];
void init(){
f[0] = 1;
for(int i=1;i<=1000000;i++)
f[i] = f[i-1] * p;
}
void solve_hash(){
ULL temp = 0;
int t = strlen(s1+1);
for(int i=1;i<=t;i++)
temp = temp * p + s1[i];
has[0] = 0;
int len = strlen(s2+1);
for(int i=1;i<=len;i++)
has[i] = has[i-1] * p + s2[i];
//计算一个串在另一个串里的次数
int ans = 0;
for(int i=t;i<=len;i++)
if(temp == (has[i] - has[i-t] * f[t])) ans++;
printf("%d\n", ans);
}
方法2:
p取一个6到8位的素数,mod取一个大素数,一般取1e9+7或1e9+9
安全指数:四星 (还可以)
但是字符串长度>=1e5,时间上就虚了。。
hash[i]=(hash[i−1]×p+idx(s[i]))%mod
求区间:
hash[L,R]=hash[R]−hash[L−1]∗p(R−L+1)
但是字符串长度>=1e5,取膜太多,时间上就虚了。。
const int Maxn = 1e4 + 10;
const LL p = 31;
const LL mod = 1e9 + 7;
char s1[Maxn], s2[Maxn*100];
LL h1[Maxn], h2[Maxn*100], f[Maxn*100];
void init(){
h1[0] = h2[0] = 0;
f[0] = 1;
for(int i=1;i<=1000000;i++) f[i] = f[i-1] * p % mod;
}
LL idx(char x){
return (long long)(x - 'A' + 1);
}
void Hash(char s[], LL has[]){
int len = strlen(s+1);
for(int i=1;i<=len;i++)
has[i]=(has[i-1]*p+idx(s[i])) % mod;
}
LL get_L_to_R(int Left, int Right, LL has[]){
return (has[Right] - has[Left-1]* f[Right - Left + 1] % mod + mod) % mod;
}
void solve(){
int ans = 0;
int tmp = strlen(s1+1);
LL temp = get_L_to_R(1, tmp, h1), tp;
int len = strlen(s2+1);
for(int i=tmp;i<=len;i++){
tp = get_L_to_R(i-tmp+1, i, h2);
if(temp == tp) ans++;
}
printf("%d\n",ans);
}
方法3:
我感觉。。太暴力了。。
hash取法三
double hash
即取两个mod值,mod1和mod2
hash1[i]=(hash1[i-1]*p+idx(s[i]))%mod1
hash2[i]=(hash2[i-1]*p+idx(s[i]))%mod2
mod1一般取1e9+7,mod2一般取1e9+9为什么这么取?
1000000007和1000000009是一对孪生素数,取它们,冲突的概率极低!
安全指数:五星!(非常稳!)(稳啊…稳T了…开玩笑)
但是确实稳,反正不会wa
AC代码:
#include<iostream>
#include<cstdio>
#include<queue>
#include<vector>
#include<string.h>
#include<algorithm>
using namespace std;
typedef pair<int, int> PII;
typedef unsigned long long ULL;
typedef long long LL;
#define mem(a,b) memset(a, b, sizeof(a))
#define LMid Left, Mid
#define RMid Mid+1,Right
#define Lson num<<1, Left, Mid
#define Rson num<<1|1, Mid + 1, Right
const int Maxn = 1e4 + 10;
const ULL p = 31;
char s1[Maxn], s2[Maxn*100];
ULL has[Maxn*100], f[Maxn*100];
void init(){
f[0] = 1;
for(int i=1;i<=1000000;i++)
f[i] = f[i-1] * p;
}
void solve_hash(){
ULL temp = 0;
int t = strlen(s1+1);
for(int i=1;i<=t;i++)
temp = temp * p + s1[i];
has[0] = 0;
int len = strlen(s2+1);
for(int i=1;i<=len;i++)
has[i] = has[i-1] * p + s2[i];
//计算一个串在另一个串里的次数
int ans = 0;
for(int i=t;i<=len;i++)
if(temp == (has[i] - has[i-t] * f[t])) ans++;
printf("%d\n", ans);
}
int main(){
init();
int T;
scanf("%d", &T);
while(T--){
scanf("%s%s",s1+1,s2+1);
solve_hash();
}
return 0;
}