跳到正文

题解

Lozinke(hash)

zzr8178541919约 3 分钟
原文
文章信息与版本

文章信息

发布
2019年11月3日
收录
2025年12月12日
更新
2026年11月21日
篇幅
约 3 分钟
获赞
3
题目
P4421

版本

  1. v1当前

这是hash的一道非常好的题

看到一道没什么思路的题目时,一定不要想着去看题解。要敢于尝试,说不定暴力一下就过了呢?

首先我们预处理出所有的连续子串的hash值。这个直接暴力即可。

然后对于每一个字符串,我们可以二分来找到那些字符串的hash值相同的字符串。可以用stl的函数,我用的是手写。

主要就是hash值得处理,一共只会有26种字母,所以我在这用的是以26位进制的处理方式。这样可以保证hash出来的值具有独特性。

!!! 要记得开 long long,不然会wa两个点。

C++
#include<cmath>
#include<cstring>
#include<cstdio>
#include<iostream>
#include<algorithm>
#define int long long 
using namespace std;
char a[20005][15];
int b[2000005];
int sum=0;
int wns[2000005];
int Find(int val)
{
	int l=1;
	int r=sum;
	while(l<r)
	{
		int mid=(l+r)/2;;
		if(wns[mid]<val)
		l=mid+1;
		else
		r=mid;
	}
	return l;
}
signed main()
{
	int n;
	scanf("%lld",&n);
	for(int i=1;i<=n;i++)
	{
		cin>>(a[i]+1);
	}
	for(int i=1;i<=n;i++)
	{
		int now=0;
		int len=strlen(a[i]+1);
		for(int j=1;j<=len;j++)
		{
			int t=len-j+1;
			int p=a[i][j]-'a'+1;
			b[++now]=p;
			for(int k=2;k<=t;k++)
			{
				p=p*26+a[i][k+j-1]-'a'+1;
				b[++now]=p;
			}
		}
		sort(b+1,b+now+1);
		for(int j=1;j<=now;j++)
		{
			if(b[j]!=b[j-1])
			wns[++sum]=b[j];
		}
	}
	int ans=-n;
	sort(wns+1,wns+1+sum);
	for(int i=1;i<=n;i++)
	{
		int nowp=a[i][1]-'a'+1;
		int len=strlen(a[i]+1);
		for(int j=2;j<=len;j++)
		{
			nowp=nowp*26+a[i][j]-'a'+1;
		}
		int t=Find(nowp);
		while(wns[t]==nowp)
		{
			ans++;
			t++;
		}
	}
	printf("%lld\n",ans);
	return 0;
}
原文