题目链接:点击查看
题目大意:给出 n 个字符串,定义函数 f( s , t ) 为字符串 s 的前缀和字符串 t 的后缀所能匹配的最大长度,现在求
题目分析:因为总的前缀和后缀的个数都为 个,所以我们可以预处理时将所有的后缀的哈希扔到 map 里计数,然后遍历每个前缀,记录和当前前缀相等的后缀有多少个,不过会出现重复计算的问题,例如对于字符串 s = "aba" 来说,f ( s , s ) 应该是 3 才对,但是当长度为 1 时,s[ 1 ] = s[ 3 ] = ' a ' 因为也满足前缀和后缀相等的条件,所以也会被计算到答案中去,为了去重,我们可以用 next 进行去重,只需要使得 cnt[ next[ i ] ] -= cnt[ i ] 即可,具体原理自己在纸上画一下不难看出,这里不多赘述了
代码:
#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<cassert>
using namespace std;
typedef long long LL;
typedef unsigned long long ull;
const int inf=0x3f3f3f3f;
const int N=1e5+100;
const int mod=998244353;
map<ull,int>mp;
string s[N];
int nt[N*10],cnt[N*10];
void Hash(string& s)
{
ull hash=0,p=1;
for(int i=s.size()-1;i>=0;i--)
{
hash+=(s[i]-'a'+1)*p;
p*=131;
mp[hash]++;
}
}
void get_next(string& s)
{
nt[0]=-1;
int i=0,j=-1;
while(i<s.size())
{
if(j==-1||s[i]==s[j])
nt[++i]=++j;
else
j=nt[j];
}
}
int main()
{
#ifndef ONLINE_JUDGE
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
#endif
// ios::sync_with_stdio(false);
int n;
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>s[i];
Hash(s[i]);
}
LL ans=0;
for(int i=1;i<=n;i++)
{
get_next(s[i]);
ull hash=0;
for(int j=0;j<s[i].size();j++)
{
hash=hash*131+s[i][j]-'a'+1;
cnt[j+1]=mp[hash];
}
for(int j=1;j<=s[i].size();j++)
cnt[nt[j]]-=cnt[j];
for(int j=1;j<=s[i].size();j++)
ans=(ans+1LL*cnt[j]*j%mod*j%mod)%mod;
}
cout<<ans<<endl;
return 0;
}