【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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值