P3370 【模板】字符串哈希 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)
字符串哈希法
#define _CRT_SECURE_NO_WARNINGS 1.
#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ULL;
typedef long long LL;
const int N = 10001;
const int P = 233;
LL h[N], p[N];
char a[N];
ULL haxi(char s[])
{
ULL len = strlen(s);
ULL ans = 0;
for (LL i = 0; i < len; i++)
{
ans = P*ans +(ULL)s[i];
}
return ans;
}
int main()
{
//cin.tie(nullptr)->sync_with_stdio(false);
int n; scanf("%d",&n);
for (int i = 1; i <= n; i++)
{
scanf("%s", a);
h[i] = haxi(a);
}
sort(h + 1, h + 1 + n);
LL ans = 1;
for (LL i = 1; i <n; i++)
{
if (h[i] != h[i + 1])ans++;
}
cout << ans;
return 0;
}
当然,想写简单点也有其他方法:
set
#include<bits/stdc++.h>
using namespace std;
set<string>se;
int main()
{
int n;cin>>n;
for(int i=1;i<=n;i++)
{
string s;cin>>s;
se.insert(s);
}
cout<<se.size();
return 0;
}