【bzoj3796】Mushroom追妹纸 hash+二分答案

嗯,好久没写hash了。

先处理出s3在s1和s2的位置,然后二分答案,看有没有s1和s2有没有公共子串不包含就可以了。


#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<iostream>
#include<algorithm>
#include<vector>
#define maxn 50010
#define mod 10007

using namespace std;

vector<int> v[mod];
char s1[maxn],s2[maxn],s[maxn];
int hash11[maxn],hash21[maxn];
int p1[maxn];
unsigned long long p2[maxn],hash12[maxn],hash22[maxn];
int n,m;
unsigned long long Hash;
bool vis1[maxn],vis2[maxn];
int next1[maxn],next2[maxn];
int hash,len1,len2,len;

int calc11(int l,int r)
{
	l++;r++;
	return (hash11[r]-hash11[l-1]*p1[r-l+1]%mod+mod)%mod; 
}

int calc21(int l,int r)
{
	l++;r++;
	return (hash21[r]-hash21[l-1]*p1[r-l+1]%mod+mod)%mod;
}

unsigned long long calc12(int l,int r)
{
	l++;r++;
	return hash12[r]-hash12[l-1]*p2[r-l+1];
}

unsigned long long calc22(int l,int r)
{
	l++;r++;
	return hash22[r]-hash22[l-1]*p2[r-l+1];
}

bool query(int l,int r)
{
	int x=calc21(l,r),y=calc22(l,r);
	for (int i=0;i<v[x].size();i++)
	  if (v[x][i]==y) return 1;
	return 0;
}

bool check(int x)
{
	if (x==0) return 0;
	for (int i=0;i<mod;i++) v[i].clear();
	for (int i=0;i+x-1<len1;i++)
	  if (next1[i]==len1 || i+x-1<next1[i]+len-1)
	    v[calc11(i,i+x-1)].push_back(calc12(i,i+x-1));
	for (int i=0;i+x-1<len2;i++)
	  if (next2[i]==len2 || i+x-1<next2[i]+len-1)
	    if (query(i,i+x-1)) return 1;
	return 0;
}

int main()
{
	scanf("%s%s%s",s1,s2,s);
	len=strlen(s);len1=strlen(s1);len2=strlen(s2);
	for (int i=1;i<=len1;i++) hash11[i]=(hash11[i-1]*233+s1[i-1]-'a')%mod;
	for (int i=1;i<=len1;i++) hash12[i]=hash12[i-1]*2333+s1[i-1]-'a';
	for (int i=1;i<=len2;i++) hash21[i]=(hash21[i-1]*233+s2[i-1]-'a')%mod;
	for (int i=1;i<=len2;i++) hash22[i]=hash22[i-1]*2333+s2[i-1]-'a';
	for (int i=1;i<=len;i++) hash=(hash*233+s[i-1]-'a')%mod,Hash=Hash*2333+s[i-1]-'a';

	p1[0]=1;p2[0]=1;
	for (int i=1;i<=max(len,max(len1,len2));i++) p1[i]=p1[i-1]*233%mod,p2[i]=p2[i-1]*2333;
	for (int i=0;i+len-1<len1;i++) if (calc11(i,i+len-1)==hash && calc12(i,i+len-1)==Hash) vis1[i]=1;
	for (int i=0;i+len-1<len2;i++) if (calc21(i,i+len-1)==hash && calc22(i,i+len-1)==Hash) vis2[i]=1;
	next1[len1]=len1;for (int i=len1-1;i>=0;i--) if (vis1[i]) next1[i]=i; else next1[i]=next1[i+1];
	next2[len2]=len2;for (int i=len2-1;i>=0;i--) if (vis2[i]) next2[i]=i; else next2[i]=next2[i+1];
	
	int l=0,r=min(len1,len2),ans;
	while (l<=r)
	{
		int mid=(l+r)/2;
		if (check(mid)) ans=mid,l=mid+1;
		else r=mid-1;
	}
	printf("%d\n",ans);
	return 0;
}


你可能感兴趣的:(【bzoj3796】Mushroom追妹纸 hash+二分答案)