【ybt高效进阶2-2-1】字符串哈希

字符串哈希

题目链接:ybt高效进阶2-2-1

题目大意

给出一堆字符串,问你有多少个不同的。

思路

这道题很明显就是一道 hash。

我们随便弄一个值数,然后对于每个字符串有一个 hash 值。
(相同的字符串的 hash 值一定相同,不同的字符串的 hash 值一般不同,就也可能相同)

那我们就只用跟前面有他的 hash 值的字符串看是否相同就可以了。

(至于记录一个 hash 值有哪些字符串,我用的是邻接表在存)

代码

#include<cstdio>
#include<cstring>
#define mo 19491001
#define ll long long

using namespace std;

struct node {
    
    
	int to, nxt;
}e[10001];
int n, ans, hash[19491010], size, KK, sizee;
ll hash_num, times;
char c[10001][1501];
bool yes, same;

void push(int x, int y) {
    
    //邻接表记录同一个hash值有哪些字符串
	e[++KK] = (node){
    
    y, hash[x]}; hash[x] = KK;
}

int main() {
    
    
	scanf("%d", &n);
	for (int i = 1; i <= n; i++) {
    
    
		scanf("%s", c[i]);
		size = strlen(c[i]);
		
		hash_num = 0ll;
		times = 1ll;
		for (int j = 0; j < size; j++) {
    
    //得出hash值
			hash_num = (hash_num + (times * c[i][j]) % mo) % mo;
			times = (times * 307ll) % mo;
		}
		
		if (hash[hash_num]) {
    
    //之前有这个hash值,与哪些有这个值的字符串进行配对,看有没有出现过
			same = 0;
			for (int j = hash[hash_num]; j; j = e[i].nxt) {
    
    
				sizee = strlen(c[e[j].to]);
				if (size == sizee) {
    
    
					yes = 1;
					for (int k = 0; k < size; k++)
						if (c[i][k] != c[e[j].to][k]) {
    
    
							yes = 0;
							break;
						}
					if (yes) {
    
    //出现过
						same = 1;
						break;
					}
				}
			}
			if (!same) {
    
    //没有出现过,是新的字符串
				push(hash_num, i);
				ans++;
			}
		}
		else {
    
    //之前没有这个hash值,是新的字符串
			push(hash_num, i);
			ans++;
		}
	}
	
	printf("%d", ans);
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43346722/article/details/112900083