跳到正文

个人记录

字符串哈希总结

the133lvlone约 1 分钟
原文
文章信息与版本

文章信息

发布
2025年10月4日
收录
2026年10月11日
更新
2026年11月11日
篇幅
约 1 分钟

版本

  1. v1当前

总结

php
字符串哈希,是吧字符串转成数字的方式
使用函数为a[i]=a[i-1]*b+c;
b,c自己决定,取模使用unsigned long long的自然溢出
a为字符串的哈希函数
(i>1)时a[i]为字符串的第0-i位的哈希值,a[0]=字符串的第0位

T2

C++
#include<bits/stdc++.h>
#define con continue
#define int unsigned long long
//#define double long double
using namespace std;
const string A[]={"Yes\n","No\n"};
int n,a[16021602],l,L,r,R,d[1000602]; 
string p;
int D(int l,int r)
{
	return a[r]-a[l-1]*d[r-l+1];
}
signed main()
{
	d[0]=1;
	cin>>p>>n;
	p='.'+p;
	for(int i=1;i<p.size();i++)
	{
		d[i]=d[i-1]*293;
		a[i]=a[i-1]*293+p[i];
	}
	while(n--)
	{
		cin>>l>>r>>L>>R;
		cout<<A[D(l,r)!=D(L,R)];
	}
	return 0;
}
php
因为前i位字符串哈希类似于前缀和,所以可以使用类似前缀和的方式来算出哈希值
原文