字符串哈希初步

初始字符串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

 hash的多种使用姿势:

1,开散列hash:类似邻接表存图。可以看这个雪花雪雪花

2,子串hash:把所有前缀的hash都搞出来,然后进行代数运算即可。例题:Palindrome

3,二维hash,看这个博客

posted @ 2018-05-19 20:41  garage  阅读(135)  评论(0编辑  收藏  举报