题目链接:
tokitsukaze and Similar String
题意:
tokitsukaze获得了一个长度为n (1≤n≤10^5),由a-z小写字母组成的字符串。
我们定义两个字符串是相似的,当且仅当能通过多次以下操作,使得两个字符串相等。并且把需要操作的最小次数,称为两个字符串的相似度。
操作是这样的:选择一个字符串,把字符串的每个字母都替换为字母表上的下一个字母,同时,我们认为z的下一个字母为a,比如选择"acdz",操作一次后变为"bdea"。
现在tokitsukaze从字符串中任取两个子串,她想知道它们是不是相似的,如果它们相似,请输出相似度,如果它们不相似,请输出-1。
思路:
字符串哈希。
预处理26种变化的Hash表,每次询问用Hash表来判断子串是否相等。若 x 的第 i 种变化与 y 相等,ans=min(i,26-i) 。
Code:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int MAX = 1e5+10;
const ll mod = 1e9+7;
const ull P = 131;
int n,q;
char s[MAX];
ull Hash[MAX][30];
ull pw[MAX];
ull get(int l,int r,int t){
return Hash[r][t]-Hash[l-1][t]*pw[r-l+1];
}
int main()
{
scanf("%d%s%d",&n,s+1,&q);
pw[0]=1;
for(int i=1;i<=n;i++){
for(int j=0;j<26;j++){
Hash[i][j]=Hash[i-1][j]*P+(s[i]-'a'+1+j)%26;
if((s[i]-'a'+1+j)%26==0) Hash[i][j]+=26;
}
pw[i]=pw[i-1]*P;
}
while(q--){
int x,y,len;
scanf("%d%d%d",&x,&y,&len);
int t = ((s[y]-'a'+1+26)-(s[x]-'a'+1))%26;
if(get(x,x+len-1,t)==get(y,y+len-1,0)){
printf("%d\n",min(t,26-t));
}
else{
printf("-1\n");
}
}
return 0;
}