字符串哈希 模板

版权声明:https://blog.csdn.net/huashuimu2003 https://blog.csdn.net/huashuimu2003/article/details/84893177

模板

#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
const int maxn=2e4+10;
const int inf=0x7ffffff;
inline int read()
{
	int f=1,num=0;
	char ch=getchar();
	while (!isdigit(ch)) { if (ch=='-') f=-1; ch=getchar(); }
	while (isdigit(ch)) num=(num<<1)+(num<<3)+(ch^48), ch=getchar();
	return num*f;
}
char s[maxn];
ull a[maxn];
ull base=13331;
ull Hash()
{
    int len=strlen(s);
    ull hash=0;
    for(int i=0;i<len;i++)
        hash=hash*base+s[i];
    return hash&inf;
}

int main()
{
    int n=read();
    for(int i=0;i<n;i++)
	{
        cin>>s;
        a[i]=Hash();
    }
    sort(a,a+n);
    int ans=1;
    for(int i=1;i<n;i++)
        if(a[i]!=a[i-1]) ++ans;
    printf("%d\n",ans);
    return 0;
}

转自大佬https://blog.csdn.net/qq_38891827/article/details/80723483

//暂时没用到双hash,用到会过来补充
//hash一般用来解决字符串判重/字符串匹配问题
//遇见不定长问题可通过二分+hash降低复杂度
//遇见定长字符串问题可通过尺取+hash来降低复杂度
//二维hash的时候尺取方法就是把之前不需要的都变为0再加上当前行,
//将匹配字符串整体下移,来验证hash值是否相等
#include<string.h>
typedef unsigned long long ull;
const int maxn=1e5+5;
ull hash_[maxn],xp[maxn];
void init()
{
    xp[0]=1;
    for(int i=1;i<maxn;i++)
        xp[i]=xp[i-1]*13331;//这里13331玄学数字,大概可以随意换
    return ;
}
void make_hash(char str[])//处理出str的hash值
{
    int len=strlen(str);
    hash_[len]=0;
    for(int i=len-1;i>=0;i--)
    {
        hash_[i]=hash_[i+1]*13331+str[i]-'A'+1;
    }
    return ;
}
ull Get_hash(int i,int L)//得到起点为i,长度为L的子串的hash值
{
    return hash_[i]-hash_[i+L]*xp[L];
}

例题

题目

http://acm.hdu.edu.cn/showproblem.php?pid=1686

代码

#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long ull;
const int maxn = 1e6+5;
ull xp[maxn],hash_1[maxn],hash_2[maxn];
void init()
{
    xp[0]=1;
    for(int i=1;i<maxn;i++)
        xp[i]=xp[i-1]*13331;
}
ull get_hash(int i,int L,ull hash_[])//get_hash(i,L)可以得到从位置i开始的,长度为L的子串的hash值.
{
    return hash_[i]-hash_[i+L]*xp[L];
}
int make_hash(char str[],ull hash_[])
{
    int len=strlen(str);
    hash_[len]=0;
    for(int i=len-1;i>=0;i--)
        hash_[i]=hash_[i+1]*13331+(str[i]-'a'+1);
    return len;
}
char str[maxn],str2[maxn];
int main()
{
    init();
    int t;
    scanf("%d",&t);
    while(t--)
    {
        int ans=0;
        scanf("%s%s",str,str2);
        int len1=make_hash(str,hash_1);
        int len2=make_hash(str2,hash_2);
        ull tmp=get_hash(0,len1,hash_1);
        for(int i=0;i<len2-len1+1;i++)//注意枚举时的边界问题
            if(get_hash(i,len1,hash_2)==tmp)
                ans++;
        printf("%d\n",ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/huashuimu2003/article/details/84893177