题目
https://www.luogu.com.cn/problem/P3370
思路
大致的方法就是先自己预定一个base基值,将字符串的每一位与base相乘,解决冲突的方法就是使用自然溢出、双哈希等
代码
自然溢出
#include<iostream> #include<cstdio> #include<cstring> #include<string> #include<algorithm> using namespace std; #define ull unsigned long long ull base = 131; ull list[20000]; int answer = 0,n; long long a[20000]; int hashsssss(string a) { ull ans = 0; for (int i = 0; i < a.length(); i++) { ans = ans * base+(ull)a[i]; } return ans & 0x7fffffff; } int main() { scanf("%d", &n); for (int i = 0; i < n; i++) { string temp; cin >> temp; a[i] = hashsssss(temp); } sort(a, a + n); int count = 1; for (int i = 0; i < n - 1; i++) if (a[i] != a[i + 1])count++; printf("%d", count); }
双哈希
#include<iostream> #include<cstdio> #include<cstring> #include<string> #include<algorithm> using namespace std; #define ull unsigned long long ull base = 131; ull mod1 = 192837423; ull mod2 = 192348236; struct node { ull x; ull y; }a[20000]; int answer = 0, n; bool cmp(struct node &a, struct node &b) { if (a.x == b.x)return a.y > b.y; else return a.x > b.x; } int hashsssss(string a) { ull ans = 0; for (int i = 0; i < a.length(); i++) { ans = ans * base + (ull)a[i]%mod1; } return ans; } int hashsssss2(string a) { ull ans = 0; for (int i = 0; i < a.length(); i++) { ans = ans * base + (ull)a[i] % mod2; } return ans; } int main() { scanf("%d", &n); for (int i = 0; i < n; i++) { string temp; cin >> temp; a[i].x = hashsssss(temp); a[i].y = hashsssss2(temp); } sort(a, a + n,cmp); int count = 1; for (int i = 0; i < n - 1; i++) if (a[i].x != a[i + 1].x|| a[i].y != a[i + 1].y)count++; printf("%d", count); }