【Hash】【字符串】字符串哈希

L i n k Link

l u o g u luogu P 3370 P3370

D e s c r i p t i o n Description

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

I n p u t Input

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

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

O u t p u t Output

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

S a m p l e Sample I n p u t Input

5
abc
aaaa
abc
abcc
12345

S a m p l e Sample O u t p u t Output

4

H i n t Hint

时空限制:1000ms,128M

数据规模:

对于30%的数据:N<=10,Mi≈6,Mmax<=15;

对于70%的数据:N<=1000,Mi≈100,Mmax<=150

对于100%的数据:N<=10000,Mi≈1000,Mmax<=1500

样例说明:

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

T r a i n Train o f of T h o u g h t Thought

计算字符串的 H a s h Hash 值,判断在这个 H a s h Hash 值下,有没有相同的字符串,没有则假如这个值的数组,并且加一下答案

C o d e Code

#include<cstdio>
#include<iostream>
using namespace std;
int H[50005],n,ans;
long long P=10007;
string S[50008][5];
string s;

int main()
{
	cin >> n; 
	
	for (int i = 1; i <= n; ++i) {
		int hashz = 0 ,b = 0;//hashz为字符串的hash值,b为是否此字符串出现过
		cin >> s;
		for (int j = 0; j < (int)s.size(); ++j) 
			hashz = (hashz * 10 + s[j]) % P;//计算Hash值
			
		for (int j = 1; j <= H[hashz]; ++j)
			if (s == S[hashz][j]) {
				b = 1;
				break;
			}
			
		if (!b) {
			S[hashz][++H[hashz]] = s;
			++ans;
		}
	}
	
	cout << ans;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/LTH060226/article/details/99232203