思路分析
先把每一个后缀的hash值存起来,然后枚举$s[i]$的每一个前缀,记录有多少个后缀能够匹配,但是不能直接计算贡献,因为同一个字符串可能匹配到多个前缀,所以要进行去重
比如 $aba$就会同时计算$a$和$aba$,实际上只取最长的那个,可以通过next数组进行去重,$cnt[next[i]]-=cnt[i]$
AC代码
#include <bits/stdc++.h>
#define fi first
#define se second
#define ll long long
#define pb push_back
#define mp make_pair
#define fun function
#define sz(x) (x).size()
#define lowbit(x) (x)&(-x)
#define all(x) (x).begin(),(x).end()
#define mem(a,b) memset(a,b,sizeof(a))
namespace FastIO {
#define BUF_SIZE 100000
#define OUT_SIZE 100000
bool IOerror=0;
inline char nc() {
static char buf[BUF_SIZE],*p1=buf+BUF_SIZE,*pend=buf+BUF_SIZE;
if(p1==pend) {
p1=buf;
pend=buf+fread(buf,1,BUF_SIZE,stdin);
if(pend==p1) {
IOerror=1;
return -1;
}
}
return *p1++;
}
inline bool blank(char ch) {
return ch==' '||ch=='\n'||ch=='\r'||ch=='\t';
}
template<class T> inline bool read(T &x) {
bool sign=0;
char ch=nc();
x=0;
for(; blank(ch); ch=nc());
if(IOerror)return false;
if(ch=='-')sign=1,ch=nc();
for(; ch>='0'&&ch<='9'; ch=nc())x=x*10+ch-'0';
if(sign)x=-x;
return true;
}
template<class T,class... U>bool read(T& h,U&... t) {
return read(h)&&read(t...);
}
#undef OUT_SIZE
#undef BUF_SIZE
};
using namespace std;
using namespace FastIO;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int INF = 0x3f3f3f3f;
const int N = 1e6+10;
const int P = 998244353;
const ll base = 1331;
typedef unsigned long long ull;
int nex[N];
map<ull,int>cnt;
ll sum[N];
string s[N];
void ins(string x) {
ull hash=0,ba=1;
int len=sz(x);
for(int i=len-1; i>=0; i--) {
hash=x[i]*ba + hash;
ba=ba*base;
cnt[hash]++;
}
}
void getnext(string x) {
int j=nex[0]=-1;
int len=sz(x);
for(int i=1; i<len; i++) {
while(j>-1 && x[i]!=x[j+1]) j=nex[j];
if(x[i]==x[j+1]) j++;
nex[i]=j;
}
}
signed main() {
#ifdef xiaofan
freopen("1.in","r",stdin);
freopen("1.out","w",stdout);
#endif
int n;
cin>>n;
for(int i=1; i<=n; i++) {
cin>>s[i];
ins(s[i]);
}
ll ans=0;
for(int i=1; i<=n; i++) {
getnext(s[i]);
ull hash=0;
int len=s[i].size();
for(int j=0; j<len; j++) {
hash=hash*base+s[i][j];
sum[j]=cnt[hash];
}
for(int j=0; j<len; j++) {
if(nex[j]==-1) continue;
sum[nex[j]]-=sum[j];
}
for(int j=0; j<len; j++) ans=(ans + 1LL*sum[j]*(j+1)*(j+1)%P) %P;
}
cout<<ans<<endl;
return 0;
}