

关键是如何构造哈希值能使所有情况尽可能地少重复,下面是常用的哈希方法:

我在这题中用的是自然溢出方法,下面是代码:
#include<iostream>
#include<cstring>
#include<set>
using namespace std;
typedef unsigned long long ull;
set<ull> st;
const int p = 23;//设定一个素数
//const int mod;//设定一个模
ull hash[1505];//利用ull的溢出机制
char dat[1505];
int main()
{
int n;
cin>>n;
for(int i=1;i<=n;++i)
{
cin>>dat;
hash[0]=dat[0];
for(int i=1;i<strlen(dat);++i)
{
hash[i]=hash[i-1]*p+dat[i];
}
st.insert(hash[strlen(dat)-1]);
}
cout<<st.size()<<endl;
return 0;
}
本文介绍了一种使用自然溢出方法的哈希算法实现,并通过一个具体示例展示了如何计算字符串的哈希值来减少重复,最后输出不重复元素的数量。

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



