其他分享
首页 > 其他分享> > 字符串哈希

字符串哈希

作者:互联网

视频链接:

 

 

 

 

 

 

#include <iostream>
using namespace std;

typedef unsigned long long ULL;
const int N = 1000010, P = 131;
int n, m;
char s[N];

// p[i]=P^i, h[i]=s[1~i]的hash值
ULL p[N], h[N];

// 预处理 hash函数的前缀和
void init(){
  p[0] = 1, h[0] = 0;
  for(int i = 1; i <= n; i ++){
    p[i] = p[i-1]*P;
    h[i] = h[i-1]*P+s[i];
  }  
}
// 计算s[l~r]的 hash值
ULL get(int l, int r){ 
  return h[r]-h[l-1]*p[r-l+1];
}
// 判断两子串是否相同
bool substr(int l1,int r1,int l2,int r2){
  return get(l1, r1) == get(l2, r2);
}

int main(){
  cin >> n >> m;
  scanf("%s", s + 1);

  init();
  while(m --){
    int a, b, c, d;
    cin >> a >> b >>c >> d;
    if(substr(a,b,c,d)) puts("Yes");
    else puts("No");
  }
  return 0;
}

P3370 【模板】字符串哈希

#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

const int N = 10010;
int n, m;
char s[N];
typedef unsigned long long ULL;
const int P = 131;
ULL h[N], ans[N];

// 计算串的哈希值
ULL calc(char *s, int n){
  h[0] = 0;
  for(int i = 1; i <= n; i ++){
    h[i] = h[i-1]*P+s[i];
  }
  return h[n];
}

int main(){
  cin >> n;
  for(int i=1; i<=n; i++){
    scanf("%s", s + 1);
    int m = strlen(s+1);
    ans[i] = calc(s, m);
  }
  
  sort(ans+1, ans+n+1);
  int cnt = 0;
  for(int i=1; i<=n; i++)
    if(ans[i]!=ans[i-1]) ++cnt;
  printf("%d", cnt);
  return 0;
}

 

标签:哈希,int,long,char,ULL,字符串,include
来源: https://www.cnblogs.com/dx123/p/16141740.html