题目描述
如果一个字符串长度为偶数,且后半部分是前半部分的循环位移,则称这个字符串为双旋转字符串,现有一个字符串集合 S S S 和字符串集合 T T T,一个集合中的字符串长度相等,求有多少对 i , j i,j i,j 满足将 S i S_i Si 和 T i T_i Ti 拼接后得到的是一个双旋转字符串。
N , M , T o t a l S , T o t a l T < = 100 , 2 < = N ∗ T o t a l S + M ∗ T o t a l T < = 4 × 1 0 6 N,M,TotalS,TotalT<=100,2<=N*TotalS+M*TotalT<=4×10^6 N,M,TotalS,TotalT<=100,2<=N∗TotalS+M∗TotalT<=4×106( N , M , T o t a l S , T o t a l T N,M,TotalS,TotalT N,M,TotalS,TotalT 分别表示 S S S 集合字串符长度, T T T 集合字串符长度, S S S 集合字串符数量, T T T 集合字串符数量),只包含小写字母,保证 N + M N+M N+M 是偶数。
题解
其实这题没什么好说的,思路很直接,先不妨假设 N ≥ M N≥M N≥M,把 T T T 中字符串哈希后存下来,算出拼接后字符串长度的一半 K K K, 对于每个 S S S 中的字符串把前 K K K 位循环位移 K K K 次的字符串全都记录下来,然后分别与后半段进行比较,若是能匹配上则去存下来的 T T T 中找能匹配后半段的数量,直接相加即可。
不过这题的数据实在是让人有点……不敢恭维。(你知道过了hack数据没过原始数据的感受吗)
其实我很少做哈希题,遇到了也是经常用各种方法偷鸡,所以这题甚至可能算是我的哈希启蒙题(?)还是调了蛮久的。
比起前缀和个人更喜欢用滑动窗口
Code
#include<bits/stdc++.h>
using namespace std;
const int N=4e6+5,K=29;
typedef unsigned long long ull;
typedef long long ll;
int n,m,len,l1,l2;
ll ans;
ull pw[N];
string s1[N];
char s2[N];
map<ull,int> mp;
map<ull,bool> b;
int main(){
cin.tie(0);
scanf("%d%d%d%d",&n,&m,&l1,&l2);
len=(l1+l2)/2;
pw[0]=1;
for(int i=1;i<=len;i++)
pw[i]=pw[i-1]*K;
if(l1<l2){
swap(n,m);
swap(l1,l2);
for(int i=1;i<=m;i++){
scanf("%s",s2+1);
ull res=0;
for(int j=1;j<=l2;j++)
res+=pw[l2-j+1+l1-len-1]*(s2[j]-'a');
mp[res]++;
}
string s;
for(int i=1;i<=n;i++){
cin>>s;
for(int j=l1-1;j>=0;j--)
s1[i]=s1[i]+s[j];
}
}
else{
for(int i=1;i<=n;i++)
cin>>s1[i];
for(int i=1;i<=m;i++){
scanf("%s",s2+1);
ull res=0;
for(int j=1;j<=l2;j++)
res+=pw[j+l1-len-1]*(s2[j]-'a');
if(!mp[res]) mp[res]=1;
else mp[res]++;
}
}
for(int i=1;i<=n;i++){
ull res=0,x=0,res1=0;
for(int j=0;j<len;j++)
res+=pw[j]*(s1[i][j]-'a');
for(int j=0;j<l1-len;j++)
res1+=pw[j]*(s1[i][j]-'a');
for(int j=len;j<l1;j++)
x+=pw[j-len]*(s1[i][j]-'a');
ull tmp=res;
b[res]=true;
ull res2=res-res1;
if(res1==x) ans+=1ll*mp[res2];
for(int j=len-1,pos=(l1-len-1+len)%len;j>=0;j--,pos=(pos-1+len)%len){
res=(res-(s1[i][j]-'a')*pw[len-1])*K+(s1[i][j]-'a');
if(b[res]) break;
b[res]=true;
res1=(res1-(s1[i][pos]-'a')*pw[l1-len-1])*K+(s1[i][j]-'a');
ull res2=res-res1;
if(l1==len) res2=res,res1=0;
if(res1==x) ans+=1ll*mp[res2];
}
b[tmp]=false;
for(int j=len-1;j>=0;j--){
tmp=(tmp-(s1[i][j]-'a')*pw[len-1])*K+(s1[i][j]-'a');
if(!b[tmp]) break;
b[tmp]=false;
}
}
printf("%lld",ans);
return 0;
}