哈希表 開放尋址法
const int null=0x3f3f3f3f;
int h[N];
// 如果x在哈希表中,返回x的下標;如果x不在哈希表中,返回x應該插入的位置
int find(int x)
{
int t = (x % N + N) % N;//N是數組長度 是個質數,一般開個兩三倍就行
while (h[t] != null && h[t] != x)
{
t ++ ;
if (t == N) t = 0;
}
return t;
}
字符串哈希
#include<iostream>
using namespace std;
typedef unsigned long long ull;
const int maxn=1e5+10,p=131;
int n,m;
ull has[maxn];
ull po[maxn];
char s[maxn];
ull get(int l,int r)
{
return has[r]-has[l-1]*po[r-l+1];//計算子串哈希值
}
int main()
{
ios::sync_with_stdio(0);//關閉同步流
cin.tie(0);
cout.tie(0);
cin>>n>>m;
cin>>s+1;
po[0]=1;
for(int i=1;i<=n;i++)
{
po[i]=p*po[i-1];//預處理次方
has[i]=s[i]+has[i-1]*p;//注意要以首字符爲最高位
}
while(m--)
{
int l1,r1,l2,r2;
cin>>l1>>r1>>l2>>r2;
if(get(l1,r1)==get(l2,r2))
cout<<"Yes";
else
cout<<"No";
if(m) cout<<endl;
}
return 0;
}