1. 程式人生 > >做題筆記 【模板】字符串哈希 - P3370

做題筆記 【模板】字符串哈希 - P3370

string out type nbsp return map har hash pre

這題的第一反應做法肯定是如題面所說:字符串hash

具體做法:

將每一個字符串化為一個k進制數,並取模一個大素數(這個素數要夠大,以免發生hash碰撞),存入數組並判重。

代碼:

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstdio>
 4 #include <cstring>
 5 using namespace std;
 6 
 7 typedef long long ll;
 8 const ll mod = 200512223;
 9
const ll base = 130; 10 11 ll pre[10001]; 12 char s[10001]; 13 14 ll hashs(char s[]) { 15 int len = strlen(s); 16 int ans = 0; 17 for (int i = 0;i < len;i++) { 18 ans = (ans * base + (ll) s[i]) % mod; 19 } 20 return ans; 21 } 22 23 int main() { 24 int n;
25 cin >> n; 26 for (int i = 1;i <= n;i++) { 27 cin >> s; 28 int ans = hashs(s); 29 pre[i] = ans; 30 } 31 sort(pre+1,pre+1+n); 32 int sum = 0; 33 for (int i = 1;i <= n;i++) { 34 if (pre[i] != pre[i-1]) { 35 sum++;
36 } 37 } 38 cout << sum; 39 return 0; 40 }

然後!今天在復習之前的課件,突然發現了map的一種騷操作:

map可以自動去重,所以只要新建一個string,int的map,並將每一個字符串存入map,最後輸出map的個數就可以了!

代碼:

 1 #include <string>
 2 #include <iostream>
 3 #include <map>
 4 #define _for(i,a,b) for (register int i = a;i <= b;i++) 
 5 using namespace std;
 6 
 7 map <string,int> m;
 8 int n,cnt; 
 9 string a;
10 
11 int main() {
12     cin >> n;
13     _for(i,1,n) {
14         cin >> a;
15         m[a] = ++cnt;
16     }
17     cout << m.size();
18     return 0;
19 }

做題筆記 【模板】字符串哈希 - P3370