初始字符串hash:

我们选定一个进制P以及膜数M

把字符串当成P进制数,以ASCII码来计算。

一般取P为131 或13331 ,M为2^64 (uLL自然溢出)

所以就这样啦~~~~~

请看代码~

 1 #include <cstdio>
 2 #include <string>
 3 #include <algorithm>
 4 #include <iostream>
 5 const int P = 131, N = 100010;
 6 typedef unsigned long long uLL;
 7 using std::string;
 8 
 9 uLL Hash[N];
10 
11 uLL gethash(string a) {
12     uLL ans = 0;
13     for(int i = 0; i < a.size(); i++) {
14         ans = ans * P + (int)(a[i]);
15     }
16     return ans;
17 }
18 
19 int main() {
20     int n; string c;
21     scanf("%d", &n);
22     for(int i = 1; i <= n; i++) {
23         std::cin >> c;
24         Hash[i] = gethash(c);
25         //printf("%lld\n", Hash[i]);
26     }
27     std::sort(Hash + 1, Hash + n + 1);
28     int ans = std::unique(Hash + 1, Hash + n + 1) - (Hash + 1);
29     printf("%d", ans);
30     return 0;
31 }洛谷P3370
洛谷P3370

相关文章: