3026: 【普及-】【P3370】字符串哈希

内存限制:128 MB 时间限制:1.000 S
评测方式:文本比较 命题人:
提交:8 解决:5

题目描述

如题,给定 lns="http://www.w3.org/1998/Math/MathML"> 个字符串(第 lns="http://www.w3.org/1998/Math/MathML"> 个字符串长度为 lns="http://www.w3.org/1998/Math/MathML">,字符串内包含数字、大小写字母,大小写敏感),请求出 lns="http://www.w3.org/1998/Math/MathML"> 个字符串中共有多少个不同的字符串。

友情提醒:如果真的想好好练习哈希的话,请自觉。

输入

第一行包含一个整数 lns="http://www.w3.org/1998/Math/MathML">,为字符串的个数。

接下来 lns="http://www.w3.org/1998/Math/MathML"> 行每行包含一个字符串,为所提供的字符串。

输出

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

样例输入 复制

5
abc
aaaa
abc
abcc
12345

样例输出 复制

4

提示

对于 lns="http://www.w3.org/1998/Math/MathML">30% 的数据:lns="http://www.w3.org/1998/Math/MathML">10lns="http://www.w3.org/1998/Math/MathML">6lns="http://www.w3.org/1998/Math/MathML">15

对于 lns="http://www.w3.org/1998/Math/MathML">70% 的数据:lns="http://www.w3.org/1998/Math/MathML">1000lns="http://www.w3.org/1998/Math/MathML">100lns="http://www.w3.org/1998/Math/MathML">150

对于 lns="http://www.w3.org/1998/Math/MathML">100% 的数据:lns="http://www.w3.org/1998/Math/MathML">10000lns="http://www.w3.org/1998/Math/MathML">1000lns="http://www.w3.org/1998/Math/MathML">1500

样例说明:

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


不使用map:

#include<bits/stdc++.h>
using namespace std;
#define MAXN 1510
#define base 261
#define mod 23333
int n,ans;
char s[MAXN];
vector<string> linker[mod+2];
inline void insert(){
	int hash=1;
    for(int i = 0;s[i];i++)
        hash =(hash*1ll*base + s[i]) % mod; //计算出字符串的Hash值
	string t=s;
	for (int i = 0; i < linker[hash].size(); i++)
	    if(linker[hash][i] == t)
		    return;
	linker[hash].push_back(t);
	ans++; 
}
int main(){
    cin >> n;
    for (int i = 1; i <= n; i++)
        cin >> s,insert();
    cout << ans << endl;
	return 0;
}

使用map:


#include<bits/stdc++.h>
using namespace std;
int n;
map<string ,int> m;
int main(){
	string s;
    cin>>n;
    for(int i=1;i<=n;i++) {
    	cin>>s;
    	m[ s ]=1;
	}
	cout<<m.size();
	return 0;
}