对于每一位(s[i])
(ans = (ans*base + (ull)s[i])\%mod + prime)
建议数值
(base = 131\
prime = 233317\
mod1 = 19260817\
mod2 = 20031101)
- 双哈希
#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#define MogeKo qwq
#define ull unsigned long long
using namespace std;
ull base = 131;
struct node {
ull x,y;
bool operator < (const node &N)const {
return x<N.x || ((x==N.x) && (y<N.y));
}
} a[10010];
char s[10010];
int n,ans;
int prime = 233317;
ull mod1 = 19260817;
ull mod2 = 20031101;
ull hash1(char s[]) {
int len = strlen(s);
ull ans = 0;
for(int i = 0; i < len; i++)
ans = (ans*base + (ull)s[i])%mod1 + prime;
return ans;
}
ull hash2(char s[]) {
int len = strlen(s);
ull ans = 0;
for(int i = 0; i < len; i++)
ans = (ans*base + (ull)s[i])%mod2 + prime;
return ans;
}
int main() {
scanf("%d",&n);
for (int i = 1; i <= n; i++) {
scanf("%s",s);
a[i].x = hash1(s);
a[i].y = hash2(s);
}
sort(a+1,a+n+1);
ans = 1;
for(int i = 1; i < n; i++) {
if(a[i].x != a[i+1].x || a[i].y != a[i+1].y)
ans++;
}
printf("%d
",ans);
return 0;
}
- 单哈希
#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#define MogeKo qwq
#define ull unsigned long long
using namespace std;
ull base = 131;
ull a[10010];
char s[10010];
int n,ans;
int prime = 233317;
ull mod = 212370440130137957ll;
ull hashi(char s[]){
int len = strlen(s);
ull ans = 0;
for(int i = 0;i < len;i++)
ans = (ans*base + (ull)s[i])%mod + prime;
return ans;
}
int main() {
scanf("%d",&n);
for(int i = 1; i <= n; i++) {
scanf("%s",s);
a[i] = hashi(s);
}
sort(a+1,a+n+1);
ans = 1;
for(int i = 1; i < n; i++) {
if(a[i] != a[i+1])
ans++;
}
printf("%d",ans);
}