随机化解决判同问题

思想类似于哈希,但是引入了随机化,每个位置的权值不再是一个数的次幂,并且需要判同的东西也不仅限于字符串,在有的时候可以巧妙的解决问题(也能解决字符串哈希)。

一道例题

随机化解决字符串哈希的代码:

#include<bits/stdc++.h>
using namespace std;
#define N 2007
#define ull unsigned long long
const int lim=2000;
set<ull> S;
char s[N];
ull w[N];
ull rn()
{
	return (ull)rand()<<31|rand();
}
int main()
{
	int n,i,j;
	srand((unsigned)time(NULL));
	scanf("%d",&n);
	for(i=1;i<=lim;i++)
		w[i]=rn();
	for(i=1;i<=n;i++)
	{
		ull sum=0;
		scanf("%s",s+1);
		int m=strlen(s+1);
		for(j=1;j<=m;j++)
			sum+=s[j]*w[j];
		S.insert(sum);
	}
	printf("%d
",(int)S.size());
	return 0;
}

update:其实本质就是一种哈希,这类问题的的关键在于能不能想到用哈希的方法,并且构造出一种正确性较高的哈希算法。
一般问题中要快速判断一组数是否和给定的一组数相同时,可以考虑哈希。

原文地址:https://www.cnblogs.com/lishuyu2003/p/11300161.html