字符串哈希

字符串哈希

例题:luogu3370

 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#include<iostream>
#include<cstring>
#include<cstdios>
#include<string>
#include<algorithm>
using namespace std;
const int maxn=10005;
typedef unsigned long long ULL;
char s[maxn];
ULL Base=62;
struct Hash
{
    inline Hash(ULL M,ULL d):Mod(M),low(d){}
    ULL Mod;
    ULL low;
    ULL pre[maxn],//pre[i] store hash of s.substr(1,i)
        Pow[maxn];//Pow[i] store 26^i
    inline ULL code()
    {
        return (pre[strlen(s)-1]-pre[0]*Pow[strlen(s)-1]%Mod+Mod)%Mod;
    }
    void init()
    {
        memset(pre,0,sizeof(pre));
        memset(Pow,0,sizeof(Pow));
        Pow[0]=1;
        pre[0]=0;
        for(int i=1; i<strlen(s); ++i)
        {
            Pow[i]=Pow[i-1]*Base;
        }
        for(int i=1; i<strlen(s); ++i)
        {
            pre[i]=(pre[i-1]*Base%Mod+s[i]-low)%Mod;
        }
    }
}h1(1e9+7,40),h2(1e9+9,47),h3(1e9+829,45);
struct str
{
    ULL c1;
    str()
    {
        c1=0; 
    } 
    str(ULL e1):c1(e1){}
}q[10050];
inline bool operator==(str a,str b)
{
    return a.c1==b.c1;
}
inline bool cmp(str f1,str f2)
{
    /*
    if(f1.c1!=f2.c1)
    {
        return f1.c1<f2.c1;
    }
    else 
    {
        if(f1.c2!=f2.c2)
        {
            return f1.c2<f2.c2;
        }
        else
            return f1.c3<f2.c3;
    }
    */
    return f1.c1<f2.c1;
}
int n;
int cnt=0;
int main()
{
    //freopen("x.txt","r",stdin);
    scanf("%d",&n);

    for(int i=1; i<=n; ++i)
    {
        memset(s,0,sizeof(s));
        s[0]='#';
        scanf("%s",s+1);
        //cout<<'\t'<<s<<endl;
        h3.init();
        q[i]=str(h3.code());
        ++cnt;
    }
    sort(q+1,q+n+1,cmp);
    for(int i=1;i<n;++i)
    {
        if(q[i]==q[i+1])--cnt;
    }
    printf("%d\n",cnt);
    return 0;
}
0%