字符串哈希
参考资料
实现
using ull=unsigned long long;
const int base=131;
const ull mod=212370440130137957;
ull get_hash(string s)
{
ull res=0;
for(int i=0;i<s.size();i++)
{
res=(res*base+s[i])%mod;
}
return res;
}
例题
洛谷 P3370 【模板】字符串哈希
如题,给定 个字符串(第 个字符串长度为 ,字符串内包含数字、大小写字母,大小写敏感),请求出 个字符串中共有多少个不同的字符串。
Code (1)
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin>>n;
set<string> s;
for(int i=1;i<=n;i++)
{
string t;
cin>>t;
s.insert(t);
}
cout<<s.size()<<'\n';
return 0;
}
洛谷 U461211 字符串 Hash(数据加强)
给定 个字符串,判断不同的字符串有多少个。
Code (1)
#include <bits/stdc++.h>
using namespace std;
using ull=unsigned long long;
const int base=131;
const ull mod=212370440130137957;
ull get_hash(string s)
{
ull res=0;
for(int i=0;i<s.size();i++)
{
res=(res*base+s[i])%mod;
}
return res;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin>>n;
map<ull,int> m;
int ans=0;
while(n--)
{
string s;
cin>>s;
ull h=get_hash(s);
if(!m[h])
{
ans++;
m[h]=1;
}
}
cout<<ans<<'\n';
return 0;
}