P3370 【模板】字串雜湊
阿新 • • 發佈:2020-10-26
首先這題不能用trie做,因為極限情況下,每一個字串的長度10000,共10000個字串,並且都不相同,那麼大約需要10000 * 10000個空間。
trie程式碼
#include<iostream> using namespace std; const int N = 300010; int son[N][62], idx; // 0~9(10), a~z(26), A~Z int cnt[N]; char str[N]; int n; int res; void insert(char str[]){ int p = 0; for(int i = 0; str[i]; i ++){ int x; if(str[i] >= 'A' && str[i] <= 'Z') x = str[i] - 'A' + 36; if(str[i] >= 'a' && str[i] <= 'z') x = str[i] - 'a' + 10; if(str[i] >= '0' && str[i] <= '9') x = str[i] - '0'; if(son[p][x] == 0) son[p][x] = ++ idx; p = son[p][x]; } cnt[p] ++; if(cnt[p] == 1) res ++; } int main(){ cin >> n; while(n --){ cin >> str; insert(str); } cout << res; return 0; }
考慮字串雜湊,用字首雜湊法。
#include<iostream> #include<algorithm> using namespace std; const int N = 10010, P = 131; #define ULL unsigned long long ULL a[N]; int n, k; char str[N]; ULL get(char str[]){ // 將str作為131進位制數,返回mod 2^64的值 ULL res = 0; for(int i = 0; str[i]; i ++) res = res * P + str[i]; return res; } int main(){ cin >> n; while(n --){ cin >> str; a[k ++] = get(str); } sort(a, a + k); int cnt = 1; for(int i = 1; i < k; i ++) if(a[i - 1] != a[i]) cnt ++; cout << cnt; return 0; }