题目链接:BZOJ 3555
这道题我们枚举字符串的每个位置,计算出删去该位置的字符后该字符串的hash值,然后排序比较字符串间的hash值是否相同即可。计算每个字符的hash值可以乘以超过字符集的素数使其自然溢出。为了让运算简单,我们可以处理每个字符之前的hash值和之后的hash值。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define ll unsigned long long//使其自然溢出
#define maxn (30000+10)
int N,M,L;
ll a[maxn][210],b[maxn][210],t[maxn];
char s[maxn];
/*
hash表
*/
inline int read(){
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
void work(int pos){//对于每个字符串的每个位置都处理其之前的hash和之后的hash
for(int i=1;i<=M;i++){
a[pos][i]=(a[pos][i-1]*149+s[i]);//只需乘以大于字符集的素数即可
}
for(int i=M;i>=1;i--){
b[pos][i]=(b[pos][i+1]*137+s[i]);
}
}
int main(){
N=read(),M=read(),L=read();
for(int i=1;i<=N;i++){
scanf("%s",s+1);
work(i);
}
int ans=0;
for(int i=1;i<=M;i++){
for(int j=1;j<=N;j++){
t[j]=(a[j][i-1]*233+b[j][i+1]*213);//枚举每个字符串去掉i位置的字符的hash值
}
sort(t+1,t+N+1);//这道题用排序就能过
int cnt=1;
for(int j=2;j<=N;j++){//统计有多少个相同的hash值
if(t[j]==t[j-1])ans+=cnt,cnt++;//若j与j-1相同,那么与之前和j-1相同的也相同
else cnt=1;
}
}
printf("%d",ans);
}