做题笔记 【模板】字符串哈希 - P3370

这题的第一反应做法肯定是如题面所说:字符串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 }

猜你喜欢

转载自www.cnblogs.com/doubeecat/p/10349045.html