P3370 【模板】字符串哈希


P3370 【模板】字符串哈希



时间限制 500ms
内存限制 125.00MB


题目描述


如题,给定\(N\)个字符串(第\(i\)个字符串长度为\(M_iMi,字符串内包含数字、大小写字母,大小写敏感),请求出\)N$个字符串中共有多少个不同的字符串。

友情提醒:如果真的想好好练习哈希的话,请自觉,否则请右转PJ试炼场:)


输入格式


第一行包含一个整数\(N\),为字符串的个数。

接下来\(N\)行每行包含一个字符串,为所提供的字符串。


输出格式


输出包含一行,包含一个整数,为不同的字符串个数。


输入输出样例


输入 #1

5
abc
aaaa
abc
abcc
12345

输出 #1

4

说明/提示


对于\(30\%\)的数据:\(N\leq 10\)\(M_i≈6\)\(M_{max}\leq 15\)

对于\(70\%\)的数据:\(N\leq 1000\)\(M_i≈100\)\(M_{max}≤150\)

对于\(100\%\)的数据:\(N\leq 10000\)\(M_i≈1000\)\(M_{max}\leq 1500\)

样例说明

样例中第一个字符串abc和第三个字符串abc是一样的,所以所提供字符串的集合为{aaaa,abc,abcc,12345},故共计\(4\)个不同的字符串。



代码


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define ull unsigned long long
const int N=1e5+5;
ull Hash[N];
int n,ans;
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;++i){
		string s;
		cin>>s;
		for(int j=0;j<s.size();++j)
			Hash[i]=(Hash[i]+s[j])*5+7;
	}
	sort(Hash+1,Hash+1+n);
	ans=n;
	for(int i=1;i<n;++i)
		if(Hash[i]==Hash[i+1]) --ans;
	printf("%d",ans);
	return 0;
}
原文地址:https://www.cnblogs.com/Potrem/p/Luogu_P3370.html