哈希思想的简单应用
hdu 1800
题意:
有n个字符串,求出出现次数最多的字符串的出现次数。
思路:
这道题可以直接用朴素算法写出,用map标记每一个字符串出现的次数,取出最大的就行。
- 朴素算法:
#include <iostream>
#include <cstdio>
#include <map>
using namespace std;
int main()
{
//freopen("in.txt","r",stdin);
int n;
map<int,int>mp;
while(scanf("%d",&n) != EOF) {
int ans = 0;
mp.clear();
for(int i = 1;i <= n; i++) {
int a;
scanf("%d",&a);
mp[a]++;
if(mp[a] > ans) {
ans = mp[a];
}
}
printf("%d\n",ans);
}
}
- 哈希算法:
此题思想就是:把字符串转化为数字,而转化的过程就是哈希,有时候会比较耗空间。
#include <iostream>
#include <cstdio>
#include <map>
using namespace std;
int n;
char str[100];
map<int,int>Hash;
int HASH(char *s)
{
int hash = 0;
int seed = 131; //素数的冲突率小
while(*s == '0') *s++;
while(*s) {
hash = hash*seed + (*s++);
}
return hash;
}
int main()
{
//freopen("in.txt","r",stdin);
while(scanf("%d",&n) != EOF) {
Hash.clear();
int ans = 0;
for(int i = 1;i <= n; i++) {
scanf("%s",str);
int k = HASH(str);
Hash[k]++;
if(Hash[k] > ans) {
ans = Hash[k];
}
}
printf("%d\n",ans);
}
return 0;
}
本文介绍了一种使用哈希算法解决寻找出现频率最高的字符串问题的方法。通过将字符串映射为整数并记录其出现次数,实现了快速查找。文章提供了两种实现方式:一种是直接使用map存储字符串及其出现次数;另一种则是利用哈希函数将字符串转化为数字,再进行统计。
&spm=1001.2101.3001.5002&articleId=75466848&d=1&t=3&u=e76cb5d1920a4cefa980636a1a9e0107)
1377

被折叠的 条评论
为什么被折叠?



