单哈希且用自然溢出代替取模操作,常数小但是容易被卡

单字符串区间内比较,查询子串hash值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
typedef unsigned long long ULL;

const int N = 100010, P = 131;

int n, m;
char str[N];
ULL h[N], p[N];

ULL get(int l, int r)
{
return h[r] - h[l - 1] * p[r - l + 1];
}

int main()
{
scanf("%d%d", &n, &m);
scanf("%s", str + 1);

p[0] = 1;
for (int i = 1; i <= n; i ++ )
{
h[i] = h[i - 1] * P + str[i];
p[i] = p[i - 1] * P;
}

while (m -- )
{
int l1, r1, l2, r2;
scanf("%d%d%d%d", &l1, &r1, &l2, &r2);

if (get(l1, r1) == get(l2, r2)) puts("Yes");
else puts("No");
}

return 0;
}

字符串双哈希,多字符串互相比较

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

const int mod = 998244353;
const ull mod1=212370440130137957ll;
const ull mod2=(1<<30);
const int base=233333;
const double eps = 1e-8;
int n, m;



struct node{ull x,y;
bool operator < (const node& a)const{
return a.x==x?a.y<y:a.x<x;
}
}f[N];
ull hash1(string s){
const int base1=1313131;
ull ans=0,len=s.size();
for(int i=0;i<len;++i)ans=(ans*base1+(ull)s[i])%mod1;
return ans;
}
ull hash2(string s){
ull ans=0,len=s.size();
const int base2=233333;
for(int i=0;i<len;++i)ans=(ans*base2+(ull)s[i])%mod2;
return ans;
}
void solve(){
cin>>n;
for(int i=1;i<=n;i++){
string s;
cin>>s;
f[i].x=hash1(s);
f[i].y=hash2(s);
}
sort(f+1,f+n+1);
int ans=0;
for(int i=1;i<=n;i++){
if(f[i].x==f[i+1].x&&f[i].y==f[i+1].y)continue;
else ans++;
}
cout<<ans<<endl;

}