1. 题目来源
相关题目:[字符串哈希+模板]字符串哈希
2. 题目解析
字符串哈希模板题,在此是直接哈希整个字符串,并加以存储。利用 vector
模拟开散列,是手写哈希表。
对于相同哈希值的字符串加以存储,再进行相等判断,不相等则说明两字符串不等,则答案 ++ 即可。
而在 [字符串哈希+模板]字符串哈希 中则更加高明,可以对于任意一个前缀进行字符串哈希来进行任意子串的判等,属于字符串哈希的进阶用法。
代码:
// https://www.luogu.com.cn/problem/P3370
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
const int N = 1505, BASE = 261, MOD = 23333;
int n, ans;
char a[N];
vector<string> h[MOD+5];
void insert() {
int hash = 1;
for (int i = 0; a[i]; i ++ ) hash = (hash * 1ll * BASE + a[i]) % MOD;
string t = a;
for (int i = 0; i < h[hash].size(); i ++ )
if (t == h[hash][i])
return ;
h[hash].push_back(t);
ans ++ ;
}
int main() {
scanf("%d", &n);
for (int i = 0; i < n; i ++ ) {
scanf("%s", a);
insert();
}
printf("%d\n", ans);
return 0;
}