【模板】字符串hash

字符串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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
using namespace std;
const int base=30;
const int mod1=19260817;
const int mod2=91815541;
const int MAXM=1505;
const int MAXN=10005;
typedef unsigned long long ull;
struct data{
ull x,y;
}ash[10010];
ull fhash1(char a[]){
ull ans=0;
int i,len=strlen(a);
for(i=0;i<len;i++)
ans=(ans*base+(ull)a[i])%mod1;
return ans;
}

ull fhash2(char a[]){
ull ans=0;
int i,len=strlen(a);
for(i=0;i<len;i++)
ans=(ans*base+(ull)a[i])%mod2;
return ans;
}

bool cmp(data a,data b)
{
return a.x<b.x;
}

void qqsort(int l,int r){
sort(ash+l,ash+r+1,cmp);
}

int main(){
int n,i,ans=0;
char t[MAXM];
scanf("%d",&n);
for(i=1;i<=n;i++){
scanf("%s",t);
ash[i].x=fhash1(t);
ash[i].y=fhash2(t);
}
qqsort(1,n);

for(i=1;i<=n;i++)
if (ash[i].x!=ash[i+1].x || ash[i+1].y!=ash[i].y)
ans++;
printf("%d",ans);
return 0;
}